iOS RSA decryption successful but the decrypted data seems corrupt

Refresh

November 2018

Views

59 time

0

The encryption algorithm that I need to implement needs to RSA encrypt a triple des key. However, I'm experiencing the following behaviour:

  1. The triple Des is created without any issues.
  2. The SecKeyGeneratePair is used to generate RSA public and private keys.
  3. The triple Des key K1 and K2 values are encrypted with a public key that is generated.
  4. I then look to decrypt the datablob created above using the private RSA key.
  5. The decryption is successful! However, the K1 and K2 values seems corrupt.

Here is the code used to encrypt the K1 and K2 data:

- (NSData *)performRsaEncryptionOnData:(NSData *)message {
    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    size_t plainBufferSize = [message length];
    uint8_t *plainBuffer = (uint8_t *)calloc(plainBufferSize, sizeof(uint8_t));
    uint8_t *cipherBuffer = (uint8_t *)calloc(cipherBufferSize, sizeof(uint8_t));
    strncpy( (char *)plainBuffer,[message bytes], plainBufferSize);
    SecKeyEncrypt(publicKey, kSecPaddingPKCS1, plainBuffer, plainBufferSize, &cipherBuffer[0], &cipherBufferSize);
    return [NSData dataWithBytesNoCopy:cipherBuffer length:cipherBufferSize];
}

Here is the code used to decrypt the data:

- (NSData *)performRsaDecryptionForDataBlob:(NSData *)encryptedData {
    size_t plainTextBufferSize = 128;
    size_t cipherBufferSize = [encryptedData length];
    uint8_t *cipherBuffer = (uint8_t*)[encryptedData bytes];
    uint8_t *plainBuffer  = (uint8_t *)calloc(plainTextBufferSize, sizeof(uint8_t));
    SecKeyDecrypt(privateKey, kSecPaddingPKCS1,cipherBuffer,cipherBufferSize,&plainBuffer[0],&plainTextBufferSize);
    return [NSData dataWithBytesNoCopy:plainBuffer length:plainTextBufferSize];
}

Here is the results that I get before RSA encryption: K1K2 = <54b86c29 f9766b00 d90a6c51 1a80026a>, after the decryption this is what we have: K1K2 = <54b86c29 f9766b00 00000000 00000000>. Frankly I'm not entirely sure why this is occuring. Any ideas?

1 answers

3

strncpy(..)не работает с двоичными данными. Ваш ключ содержит 0 и strncpy(..)останавливает копирование остальной части ключа.

K1K2 = <54b86c29 f9766b00 d90a6c51 1a80026a>
                       ^^