当使用 Apple 的 Common Crypto 和 Crypto++ 使用相同的密钥加密相同的文件(二进制数据)时,我会得到不同的结果。我使用的算法是 AES。
这是 Objective C 中使用 Common Crypto 的代码:
void FileUtil::writeToFileEncrypt(string fileName, const void *data, int size, string key, int *sizeOut)
{
int numBytesEncrypted = 0;
char keyPtr[kCCKeySizeAES256+1];
if (key.length() > 32)
{
key = key.substr(0, 32);
}
memcpy(keyPtr, key.c_str(), sizeof(keyPtr));
if (key.length() < 32)
{
for (int i = key.length(); i < 32; i++)
{
keyPtr[i] = '0';
}
}
size_t bufferSize = size + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
data, size, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
cout << "encrypt success" << endl;
}
ofstream myfile;
myfile.open (fileName.c_str(), ios::out | ios::binary);
myfile.write((const char *)buffer, numBytesEncrypted);
myfile.close();
free(buffer);
*sizeOut = numBytesEncrypted;
}
这是使用 Crypto++ 的 C++ 代码
void EncryptUtils::encrypt(string fileName, unsigned char *chars, string key, int *length, int dataLength)
{
unsigned char *iv = (unsigned char *)"0000000000000000";
char keyPtr[32 + 1];
if (key.length() > 32)
{
key = key.substr(0, 32);
}
memcpy(keyPtr, key.c_str(), sizeof(keyPtr));
if (key.length() < 32)
{
for (int i = key.length(); i < 32; i++)
{
keyPtr[i] = '0';
}
}
keyPtr[32] = '\0';
CryptoPP::AES::Encryption aesEncryption((unsigned char *)keyPtr, 32);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv);
int newBufSize = (sizeof(unsigned char *) * dataLength) + 32;
unsigned char *newBuf = (unsigned char *)malloc(newBufSize);
CryptoPP::ArraySink *arraySink = new CryptoPP::ArraySink(newBuf, newBufSize);
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, arraySink, CryptoPP::StreamTransformationFilter::PKCS_PADDING);
stfEncryptor.Put(reinterpret_cast<const unsigned char*>(chars), (unsigned int)dataLength);
stfEncryptor.MessageEnd();
*length = arraySink->TotalPutLength();
ofstream myfile;
myfile.open (fileName.c_str(), ios::out | ios::binary);
myfile.write((const char *)newBuf, *length);
myfile.close();
}
我需要让他们两个产生相同的结果。有什么我忽略的吗?