我需要实现的加密算法需要RSA加密三重密钥。但是,我遇到了以下行为:
SecKeyGeneratePair
用于生成RSA公钥和私钥。 以下是用于加密K1和K2数据的代码:
- (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];
}
以下是用于解密数据的代码:
- (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];
}
以下是我在RSA加密之前得到的结果:K1K2 = <54b86c29 f9766b00 d90a6c51 1a80026a>
,在解密之后,这就是我们所拥有的:K1K2 = <54b86c29 f9766b00 00000000 00000000>
。坦率地说,我并不完全确定为什么会这样。有什么想法吗?
答案 0 :(得分:3)
strncpy(..)
不使用二进制数据。您的密钥包含0,strncpy(..)
会停止复制密钥的其余部分。
K1K2 = <54b86c29 f9766b00 d90a6c51 1a80026a>
^^