在iOS和Android上实现相同的RSA加密

时间:2015-06-19 17:16:15

标签: android ios encryption rsa

我有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))

结果我在iOS和Android上获得了相同inputText的不同字符串。我做错了什么?

1 个答案:

答案 0 :(得分:0)

PKCS1填充在加密中添加了随机元素。如果你对同一个东西加密两次,你应该得到不同的密文。但是两个密文都应该解密到相同的明文(以增加的随机性为模,这应该由PKCS1实现来处理)。

https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding