簡體   English   中英

使用AES128加密解密NSString

[英]Decrypt NSString with AES128 encryption

我希望一個聰明的人會幫助我:)

我從C#服務器收到加密的文本,但無法正確解密:我總是有一個空字符串。 通常,解密密鑰應該是

1111111111111111

(16次)

我使用AES128算法進行解密,后端(對文本進行加密的家伙)給出的設置如下:

  • 填充:PKCS7Padding
  • 密鑰大小:128
  • InitVector:null
  • 模式:CBC
  • 要解密的文本(以base64編碼):1vycDn3ktoyaUkPlRAIlsA ==
  • 關鍵:3a139b187647a66d

這是我用於解密的代碼

- (NSData *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES2128+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

//See the doc: For block ciphers, the output size will always be less than or 
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                 keyPtr, kCCKeySizeAES128,
                                 NULL /* initialization vector (optional) */,
                                 [self bytes], dataLength, /* input */
                                 buffer, bufferSize, /* output */
                                 &numBytesDecrypted);

if (cryptStatus == kCCSuccess) {
    //the returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}

free(buffer); //free the buffer;
return nil;

}

提前感謝您的幫助。 很久以來我一直在這個問題上,我面前沒有答案...

您使用的測試輸入似乎沒有使用PKCS7填充-它沒有使用填充。 我能夠使用以下方法成功解密:

回聲1vycDn3ktoyaUkPlRAIlsA == | openssl enc -aes-128-cbc -d -a -K`echo 3a139b187647a66d | xxd -ps` -iv 0 -nosalt -nopad

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM