简体   繁体   English

iOS上的RSA加密(RSA / ECB / PKCS1Padding)

[英]RSA Encryption on iOS (RSA/ECB/PKCS1Padding)

I need to encrypt a NSString using a public key from a webserver certificate on iOS. 我需要使用iOS上的网络服务器证书中的公共密钥来加密NSString。 This is what I am doing on Android (works fine): 这是我在Android上所做的(正常工作):

public byte[] Encrypt(String plain) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {

        publicKey = "MyPublicKeyStringExtractedFromACertificate"

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

        return encryptedBytes;
}

This is what I am trying on iOS: 这是我在iOS上尝试的方法:

NSString *publicKey = @"MyPublicKeyStringExtractedFromACertificate"; // Base64 encoded key from my webserver certificate
NSData *keyData = [[NSData alloc] initWithBase64EncodedString:publicKey options:NSDataBase64DecodingIgnoreUnknownCharacters];
SecCertificateRef certificate = SecCertificateCreateWithData(kCFAllocatorDefault, ( __bridge CFDataRef) keyData); // this is returning nil

The publickey comes from a webservice certificate (on my app bundle). 公钥来自Web服务证书(在我的应用程序捆绑包中)。

What I am doing wrong? 我做错了什么? How could i use SecKeyEncrypt? 如何使用SecKeyEncrypt?

MIHCrypto has everything i need. MIHCrypto具有我需要的一切。 https://github.com/hohl/MIHCrypto https://github.com/hohl/MIHCrypto

You can't encrypt with Java Cipher using a string as the public key. 您不能使用Java Cipher使用字符串作为公用密钥进行加密。 You need a PublicKey object. 您需要一个PublicKey对象。 For example: 例如:

X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(der_bytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(publicSpec);

der_bytes needs to be in DER form, not PEM form, here. 此处,der_bytes必须采用DER形式,而不是PEM形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM