【问题标题】:Implement same RSA encryption on iOS and Android在 iOS 和 Android 上实现相同的 RSA 加密
【发布时间】:2015-09-05 18:26:24
【问题描述】:

我有用于数据编码的 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 的不同字符串。我做错了什么?

【问题讨论】:

  • 互操作性应该通过加密+欺骗来检查。
  • 你可以试试RNCryptor,因为它为所有平台提供了库,或者你可以从那里检查你的代码有什么问题。

标签: android ios encryption rsa


【解决方案1】:

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

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

【讨论】:

  • OP 不使用 OAEP,而是使用 PKCS#1 v1.5 填充,它也是随机的。它在 RFC 3447 第 7.2.1 节中进行了描述
猜你喜欢
  • 2014-08-16
  • 2019-10-12
  • 1970-01-01
  • 2015-02-27
  • 2021-08-06
  • 2019-10-03
  • 2011-12-20
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多