2015-06-19 48 views
0

我有用於數據編碼的iOS來源,並嘗試在Android應用中實現相同的編碼。 iOS版來源:在iOS和Android上實現相同的RSA加密

- (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

互操作性應該通過加密+欺騙來檢查。 –

+1

你可以嘗試[RNCryptor](https://github.com/RNCryptor),因爲它爲所有平臺提供了庫,或者你可以從那裏檢查你的代碼有什麼問題。 – Aanabidden

回答

0

PKCS1填充將隨機性元素添加到加密中。如果你兩次加密相同的東西,你應該得到不同的密文。但是這兩個密文都應該解密到相同的明文(以附加的隨機性爲模,這應該由PKCS1實現來處理)。

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

+0

OP不使用OAEP,而是PKCS#1 v1.5填充,它也是隨機的。它在RFC 3447第7.2.1節中描述 –