【问题标题】:RSA/ECB/PKCS1Padding iOS encryptionRSA/ECB/PKCS1Padding iOS 加密
【发布时间】:2014-12-30 07:19:59
【问题描述】:

我目前遇到一个涉及 iOS 加密的问题。

我的客户给了我公钥,

"-----BEGIN PUBLIC KEY-----
xxxx
-----END PUBLIC KEY-----"

需要使用的填充策略是RSA/ECB/PKCS1Padding。 使用android,这似乎很简单

cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());

return encryptedBytes;

我在 iOS 中没有看到任何直接的方法来做到这一点。像 Commoncrypto 这样使用的任何常见 pod 都不允许我强制使用 PKCS1 填充方案。作为一个非常缺乏 RSA 和加密经验的人,如果你能帮助我理解如何处理这个问题并指导我完成这个,我将不胜感激。

【问题讨论】:

标签: ios objective-c rsa rubymotion


【解决方案1】:

使用标准安全框架 - SecKeyEncryptkSecPaddingPKCS1 参数

【讨论】:

  • 我使用了上面提到的格式的公钥。我必须把它转换成别的东西吗?
  • 欧洲央行呢?如何指定这个选项?
【解决方案2】:

使用非填充解决了我的问题:

kSecPaddingNone

【讨论】:

    【解决方案3】:
    -(SecKeyRef)getPublicKeyForEncryption
    {
        NSString *thePath = [MAuthBundle pathForResource:@"certificate" ofType:@"der"];
    
        //2. Get the contents of the certificate and load to NSData
        NSData *certData = [[NSData alloc]
                            initWithContentsOfFile:thePath];
    
        //3. Get CFDataRef of the certificate data
        CFDataRef myCertData = (__bridge CFDataRef)certData;
    
        SecCertificateRef myCert;
        SecKeyRef aPublicKeyRef = NULL;
        SecTrustRef aTrustRef = NULL;
    
        //4. Create certificate with the data
        myCert = SecCertificateCreateWithData(NULL, myCertData);
    
        //5. Returns a policy object for the default X.509 policy
        SecPolicyRef aPolicyRef = SecPolicyCreateBasicX509();
    
        if (aPolicyRef) {
            if (SecTrustCreateWithCertificates((CFTypeRef)myCert, aPolicyRef, &aTrustRef) == noErr) {
                SecTrustResultType result;
                if (SecTrustEvaluate(aTrustRef, &result) == noErr) {
                    //6. Returns the public key for a leaf certificate after it has been evaluated.
                    aPublicKeyRef = SecTrustCopyPublicKey(aTrustRef);
                }
            }
        }
    
        return aPublicKeyRef;
    
    
    }
    
    -(NSString*) rsaEncryptString:(NSString*) string
    {
            SecKeyRef publicKey = [self getPublicKeyForEncryption];
    
            NSData* strData = [string dataUsingEncoding:NSUTF8StringEncoding];
    
             CFErrorRef err ;
    
             NSData * data = CFBridgingRelease(SecKeyCreateEncryptedData(publicKey, kSecKeyAlgorithmRSAEncryptionPKCS1, ( __bridge CFDataRef)strData, &err));
             NSString *base64EncodedString = [data base64EncodedStringWithOptions:0];
             return base64EncodedString;
    }
    

    【讨论】:

    • OP 明确表示他获得了一个公钥,但您提出了一个需要 DER 证书的解决方案。
    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    相关资源
    最近更新 更多