簡體   English   中英

Node.js AES解密iOS加密的NSString

[英]Node.js AES decrypt an iOS encrypted NSString

我正在像這樣對iOS中的NSString進行加密,可以很好地進行編碼和解碼:

NSString *stringtoEncrypt = @"This string is to be encrypted";
NSString *key = @"12345678901234567890123456789012";

// Encode
NSData *plain = [stringtoEncrypt dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256EncryptWithKey:key];

NSString *cipherBase64 = [cipher base64EncodedString];
NSLog(@"ciphered base64: %@", cipherBase64);

// Decode
NSData *decipheredData = [cipherBase64 base64DecodedData];
NSString *decoded = [[NSString alloc] initWithData:[decipheredData AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
NSLog(@"%@", decoded);

NSData擴展名:

- (NSData *)AES256EncryptWithKey:(NSString *)key
{
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+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 numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          keyPtr, kCCKeySizeAES256,
                                          NULL /* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

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

現在,我想將Base64編碼的字符串傳遞給Node.js並對其進行解碼。 我正在使用這種方法:

var crypto = require('crypto');

password = '12345678901234567890123456789012';
var cryptoStr = 'q6SIYHKospVNzk5ZsW8S5CURQ8qRPyDhv1TqALXhOVM=';
var iv = "0000000000000000";

var decipher = crypto.createDecipheriv('aes-256-cbc', password, iv);
var dec = decipher.update(cryptoStr,'base64','utf-8');
dec += decipher.final('utf-8'); 

console.log('Decrypted content: ' + dec);

但是結果是:

解密內容:dXYCCDBY ^ WYC要加密

任何想法是怎么回事?

在Objective-C中,您沒有定義默認為零填充IV的IV。 Node.js

keyiv必須是“二進制”編碼的字符串或緩沖區。

IV字符串中的字符0與字節\\0 您沒有傳遞填充為零的IV,而是填充了0x30字節的IV。

像這樣填寫IV:

var iv = new Buffer(16);
iv.fill(0);

暫無
暫無

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

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