在C#项目中,将为GET请求生成一个字符串,生成一个SHA256哈希并使用以下代码使用AES128进行加密:
SHA256 mySHA256 = SHA256Managed.Create();
byte[] keyHash = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(key));
byte[] keyHash128 = new byte[16];
Array.Copy(keyHash, keyHash128, 16);
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.ECB;
encryptor.Key = keyHash128;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
byte[] plainBytes = UTF8Encoding.UTF8.GetBytes(data);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = System.Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
return cipherText;
我需要在Objective-C代码中进行相同的操作。我的C代码为Objective-C代码生成输入字符串(与C#相同)。但是结果是不同的。这是我的Objective-C代码:
// const char *key - input key
// const char *content - input data
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(key, strlen(key), result);
NSData* outData = [NSData dataWithBytes:result length:16];
NSData* contentData = [NSData dataWithBytes:content length:strlen(content)];
size_t operationSize = outData.length + kCCBlockSizeAES128;
void *operationBytes = malloc(operationSize);
if (operationBytes == NULL) {
return nil;
}
size_t actualOutSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionECBMode,
outData.bytes,
kCCKeySizeAES128,
NULL,
contentData.bytes, contentData.length,
operationBytes,operationSize,&actualOutSize);
if (cryptStatus == kCCSuccess) {
decryptedData = [NSData dataWithBytesNoCopy:operationBytes length:actualOutSize];
}
结果不同。我知道问题出在我的Obj-C代码中,但我不知道在哪里。也许有人可以帮我吗?