繁体   English   中英

在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://zh.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding

暂无
暂无

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

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