在 iOS 和 Android 上实施相同的 RSA 加密
Implement same RSA encryption on iOS and Android
我有 iOS 个数据编码源,我尝试在 Android 应用程序中实现相同的编码。 iOS 来源:
- (NSString *)encryptRSA:(NSString *)plainTextString useKeyWithTag:(NSString *)tag withSecPadding:(SecPadding)padding {
SecKeyRef publicKey = [self _getPublicKeyRefByTag:tag];
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
uint8_t *cipherBuffer = malloc(cipherBufferSize);
uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
SecKeyEncrypt(publicKey,
padding,
nonce,
strlen( (char*)nonce ),
&cipherBuffer[0],
&cipherBufferSize);
NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
free(cipherBuffer);
return [encryptedData base64EncodedStringWithOptions:0];
}
函数调用:
[self.rsaManager encryptRSA:inputText withSecPadding:kSecPaddingPKCS1];
在Android我做下一个:
public static byte[] encrypt(byte[] text, PublicKey key) throws Exception {
final Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(text);
}
函数调用:
Base64.getEncoder().encodeToString(encrypt(inputText.getBytes(), publicKey))
结果,对于相同的 inputText
,我在 iOS 和 Android 上得到了不同的字符串。我做错了什么?
PKCS1 填充将随机元素添加到加密中。如果你对同一个东西加密两次,你应该得到不同的密文。但是两个密文应该解密为相同的明文(模增加的随机性,这应该由 PKCS1 实现处理)。
https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding
我有 iOS 个数据编码源,我尝试在 Android 应用程序中实现相同的编码。 iOS 来源:
- (NSString *)encryptRSA:(NSString *)plainTextString useKeyWithTag:(NSString *)tag withSecPadding:(SecPadding)padding {
SecKeyRef publicKey = [self _getPublicKeyRefByTag:tag];
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
uint8_t *cipherBuffer = malloc(cipherBufferSize);
uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
SecKeyEncrypt(publicKey,
padding,
nonce,
strlen( (char*)nonce ),
&cipherBuffer[0],
&cipherBufferSize);
NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
free(cipherBuffer);
return [encryptedData base64EncodedStringWithOptions:0];
}
函数调用:
[self.rsaManager encryptRSA:inputText withSecPadding:kSecPaddingPKCS1];
在Android我做下一个:
public static byte[] encrypt(byte[] text, PublicKey key) throws Exception {
final Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(text);
}
函数调用:
Base64.getEncoder().encodeToString(encrypt(inputText.getBytes(), publicKey))
结果,对于相同的 inputText
,我在 iOS 和 Android 上得到了不同的字符串。我做错了什么?
PKCS1 填充将随机元素添加到加密中。如果你对同一个东西加密两次,你应该得到不同的密文。但是两个密文应该解密为相同的明文(模增加的随机性,这应该由 PKCS1 实现处理)。
https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding