I have a basic notes app, and I want to allow the user to have encrypted or secure notes. I have an UI whipped up, but right now, I can't seem to get encryption working. Either it returns me a bunch of garbage or nothing at all. This is what I use to en/decrypt:
我有一个基本的notes应用程序,我希望允许用户使用加密或安全的笔记。我有一个UI,但是现在,我似乎无法得到加密。要么它返回给我一堆垃圾,要么什么都没有。这就是我使用的en/decrypt:
- (BOOL) encryptWithAES128Key: (NSString *) key {
// 'key' should be 16 bytes for AES128, will be null-padded otherwise
char * keyPtr[kCCKeySizeAES128+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];
// encrypts in-place, since this is a mutable data object
size_t numBytesEncrypted = 0;
CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128 , kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self mutableBytes], [self length], /* input */
[self mutableBytes], [self length] + kCCBlockSizeAES128, /* output */
&numBytesEncrypted);
return (result == kCCSuccess);
}
- (NSMutableData *) decryptWithAES128Key: (NSString *) key {
// 'key' should be 16 bytes for AES128, will be null-padded otherwise
char * keyPtr[kCCKeySizeAES128+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];
// encrypts in-place, since this is a mutable data object
size_t bufferSize = [self length] + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self bytes], [self length], /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if(result == kCCSuccess || result == kCCParamError) {
return [[NSMutableData dataWithBytesNoCopy:buffer length:numBytesEncrypted] retain];
}
return nil;
}
Does anyone have any idea why this might be going wrong?
有人知道为什么会这样吗?
Edit 1: I've revised my en/decryption code to be the same. Here is how it looks right now:
编辑1:我已经修改了我的en/解密代码是一样的。下面是它现在的样子:
- (BOOL) encryptWithAES128Key: (NSString *) key {
CCCryptorStatus ccStatus = kCCSuccess;
// Symmetric crypto reference.
CCCryptorRef thisEncipher = NULL;
// Cipher Text container.
NSData * cipherOrPlainText = nil;
// Pointer to output buffer.
uint8_t * bufferPtr = NULL;
// Total size of the buffer.
size_t bufferPtrSize = 0;
// Remaining bytes to be performed on.
size_t remainingBytes = 0;
// Number of bytes moved to buffer.
size_t movedBytes = 0;
// Length of plainText buffer.
size_t plainTextBufferSize = 0;
// Placeholder for total written.
size_t totalBytesWritten = 0;
// A friendly helper pointer.
uint8_t * ptr;
// Initialization vector; dummy in this case 0's.
uint8_t iv[kCCBlockSizeAES128];
memset((void *) iv, 0x0, (size_t) sizeof(iv));
plainTextBufferSize = [self length];
ccStatus = CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, (const void *)[key UTF8String], kCCKeySizeAES128, (const void *)iv, &thisEncipher);
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Allocate buffer.
bufferPtr = [self mutableBytes];
// Zero out buffer.
//memset((void *)bufferPtr, 0x0, bufferPtrSize);
// Initialize some necessary book keeping.
ptr = bufferPtr;
// Set up initial size.
remainingBytes = bufferPtrSize;
// Actually perform the encryption or decryption.
ccStatus = CCCryptorUpdate(thisEncipher, (const void *) [self bytes], plainTextBufferSize, ptr, remainingBytes, &movedBytes);
ptr += movedBytes;
remainingBytes -= movedBytes;
totalBytesWritten += movedBytes;
// Finalize everything to the output buffer.
ccStatus = CCCryptorFinal(thisEncipher, ptr, remainingBytes, &movedBytes);
cipherOrPlainText = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)totalBytesWritten];
NSLog(@"data: %@", cipherOrPlainText);
NSLog(@"buffer: %s", bufferPtr);
CCCryptorRelease(thisEncipher);
thisEncipher = NULL;
if(bufferPtr) free(bufferPtr);
}
- (NSMutableData *) decryptWithAES128Key: (NSString *) key {
CCCryptorStatus ccStatus = kCCSuccess;
// Symmetric crypto reference.
CCCryptorRef thisEncipher = NULL;
// Cipher Text container.
NSData * cipherOrPlainText = nil;
// Pointer to output buffer.
uint8_t * bufferPtr = NULL;
// Total size of the buffer.
size_t bufferPtrSize = 0;
// Remaining bytes to be performed on.
size_t remainingBytes = 0;
// Number of bytes moved to buffer.
size_t movedBytes = 0;
// Length of plainText buffer.
size_t plainTextBufferSize = 0;
// Placeholder for total written.
size_t totalBytesWritten = 0;
// A friendly helper pointer.
uint8_t * ptr;
// Initialization vector; dummy in this case 0's.
uint8_t iv[kCCBlockSizeAES128];
memset((void *) iv, 0x0, (size_t) sizeof(iv));
plainTextBufferSize = [self length];
ccStatus = CCCryptorCreate(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, (const void *)[key UTF8String], kCCKeySizeAES128, (const void *)iv, &thisEncipher);
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Allocate buffer.
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t) );
// Zero out buffer.
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// Initialize some necessary book keeping.
ptr = bufferPtr;
// Set up initial size.
remainingBytes = bufferPtrSize;
// Actually perform the encryption or decryption.
ccStatus = CCCryptorUpdate(thisEncipher, (const void *) [self bytes], plainTextBufferSize, ptr, remainingBytes, &movedBytes);
ptr += movedBytes;
remainingBytes -= movedBytes;
totalBytesWritten += movedBytes;
// Finalize everything to the output buffer.
ccStatus = CCCryptorFinal(thisEncipher, ptr, remainingBytes, &movedBytes);
cipherOrPlainText = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)totalBytesWritten];
NSLog(@"data: %@", cipherOrPlainText);
NSLog(@"buffer: %s", bufferPtr);
CCCryptorRelease(thisEncipher);
thisEncipher = NULL;
if(bufferPtr) free(bufferPtr);
return [NSMutableData dataWithData:cipherOrPlainText];
}
This code somewhat works. If I encrypt this string with the passphrase '1234567890123456':
这段代码有些作品。如果我用passphrase '1234567890123456'来加密这个字符串:
dict
device
Tristan's Magical Macbook of Death
text
e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcY29jb2FydGYxMDM4XGNvY29hc3VicnRm
MzYwCntcZm9udHRibFxmMFxmc3dpc3NcZmNoYXJzZXQwIEhlbHZldGljYTt9Cntc
Y29sb3J0Ymw7XHJlZDI1NVxncmVlbjI1NVxibHVlMjU1O30KXHBhcmRcdHg1NjBc
dHgxMTIwXHR4MTY4MFx0eDIyNDBcdHgyODAwXHR4MzM2MFx0eDM5MjBcdHg0NDgw
XHR4NTA0MFx0eDU2MDBcdHg2MTYwXHR4NjcyMFxxbFxxbmF0dXJhbFxwYXJkaXJu
YXR1cmFsCgpcZjBcZnMyNCBcY2YwIFx1bCBcdWxjMCBCTEFILn0=
title
Welcome to Notepaddy!
uuid
5yvghz9n4ukgefnbx0qa2xne3nxeebcmcvpci9j5lwpncul1asftdayjv8a
text
e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcY29jb2FydGYxMDM4XGNvY29hc3VicnRm
MzYwCntcZm9udHRibFxmMFxmc3dpc3NcZmNoYXJzZXQwIEhlbHZldGljYTt9Cntc
Y29sb3J0Ymw7XHJlZDI1NVxncmVlbjI1NVxibHVlMjU1O30KXHBhcmRcdHg1NjBc
dHgxMTIwXHR4MTY4MFx0eDIyNDBcdHgyODAwXHR4MzM2MFx0eDM5MjBcdHg0NDgw
XHR4NTA0MFx0eDU2MDBcdHg2MTYwXHR4NjcyMFxxbFxxbmF0dXJhbFxwYXJkaXJu
YXR1cmFsCgpcZjBcZnMyNCBcY2YwIFx1bCBcdWxjMCBCTEFILn0=
title
Welcome to Notepaddy!
uuid
5yvghz9n4ukgefnbx0qa2xne3nxeebcmcvpci9j5lwpncul1asftdayjv8a
I get the same text back, but the entire is missing and the
is cut off. Decrypting and printing the result string out gives me complete garbage when encrypted with the passphrase '0987654321123456' or any other passphrase, or the same as above when copied into the password field.
我得到了相同的文本,但是整个缺失了,被切断了。解密和打印结果字符串,在使用passphrase '0987654321123456'或任何其他密码,或在复制到密码字段时使用的任何其他密码,都给了我完整的垃圾。
5
Both versions have the same problem: You tell CommonCrypto to write past the end of your buffer, and then you ignore the result.
两个版本都有相同的问题:您告诉CommonCrypto在缓冲区的末尾写入,然后忽略结果。
The first version:
第一个版本:
[self mutableBytes], [self length] + kCCBlockSizeAES128, /* output */
The second version:
第二个版本:
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Allocate buffer.
bufferPtr = [self mutableBytes];
That's not right. You're not allocating anything. You're telling it to write bufferPtrSize
bytes to a buffer of size [self length]
!
这是不正确的。你没有分配任何东西。您是在告诉它将bufferPtrSize字节写入一个大小缓冲区(self length) !
You want to do something more like this (if you really want to encrypt in-place):
你想做一些更像这样的事情(如果你真的想要加密):
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Increase my size if necessary:
if (bufferPtrSize > self.length) {
self.length = bufferPtrSize;
}
I'm also not sure why encrypting is in-place while decrypting is not; the latter is, if anything, easier to do.
我也不知道为什么加密是正确的,而解密却不是;后者,如果有的话,更容易做到。
Your second version has an additional problems:
你的第二个版本有另外一个问题:
if(bufferPtr) free(bufferPtr);
(const void *)[key UTF8String], kCCKeySizeAES128
Additional crypto problems:
额外的加密问题:
Addendum:
附录:
The reason why you're seeing a truncated result is because you're returning a truncated answer (with PKCS7 padding, the encrypted result is always bigger than the original data). Chances (about 255/256) are that the last ciphertext block was incorrectly padded (because you gave CCryptor truncated data), so ccStatus
says an error happened but you ignored this and returned the result anyway. This is incredibly bad practice. (Additionally, you really want to use a MAC with CBC to avoid the padding oracle security hole.)
您看到一个截断结果的原因是您返回一个截断的答案(使用PKCS7填充,加密的结果总是比原始数据更大)。机会(大约255/256)是最后一个密文块被错误地填充了(因为您给了CCryptor截断的数据),所以ccStatus说一个错误发生了,但是您忽略了这个,并且返回了结果。这是非常糟糕的做法。(另外,您确实希望使用CBC的MAC来避免填充oracle安全漏洞。)
EDIT:
编辑:
Some code that seems to work looks something like this (complete with test cases):
一些看起来工作的代码看起来像这样(用测试用例完成):
Notes:
注:
[string dataUsingEncoding:NSUTF8StringEncoding]
. For bonus points, run it through CC_SHA256 and take the first 16 output bytes..
。
#include
#include
#if TARGET_OS_IPHONE
#include
#else
#include
#include
#endif
@interface NSData(AES)
- (NSData*) encryptedDataUsingAESKey: (NSData *) key;
- (NSData*) decryptedDataUsingAESKey: (NSData *) key;
@end
@implementation NSData(AES)
- (NSData*) encryptedDataUsingAESKey: (NSData *) key {
uint8_t iv[kCCBlockSizeAES128];
#if TARGET_OS_IPHONE
if (0 != SecRandomCopyBytes(kSecRandomDefault, sizeof(iv), iv))
{
return nil;
}
#else
{
int fd = open("/dev/urandom", O_RDONLY);
if (fd <0) { return nil; }
ssize_t bytesRead;
for (uint8_t * p = iv; (bytesRead = read(fd,p,iv+sizeof(iv)-p)); p += (size_t)bytesRead) {
// 0 means EOF.
if (bytesRead == 0) { close(fd); return nil; }
// -1, EINTR means we got a system call before any data could be read.
// Pretend we read 0 bytes (since we already handled EOF).
if (bytesRead <0 && errno == EINTR) { bytesRead = 0; }
// Other errors are real errors.
if (bytesRead <0) { close(fd); return nil; }
}
close(fd);
}
#endif
size_t retSize = 0;
CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], [key length],
iv,
[self bytes], [self length],
NULL, 0,
&retSize);
if (result != kCCBufferTooSmall) { return nil; }
// Prefix the data with the IV (the textbook method).
// This requires adding sizeof(iv) in a few places later; oh well.
void * retPtr = malloc(retSize+sizeof(iv));
if (!retPtr) { return nil; }
// Copy the IV.
memcpy(retPtr, iv, sizeof(iv));
result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], [key length],
iv,
[self bytes], [self length],
retPtr+sizeof(iv),retSize,
&retSize);
if (result != kCCSuccess) { free(retPtr); return nil; }
NSData * ret = [NSData dataWithBytesNoCopy:retPtr length:retSize+sizeof(iv)];
// Does +[NSData dataWithBytesNoCopy:length:] free if allocation of the NSData fails?
// Assume it does.
if (!ret) { free(retPtr); return nil; }
return ret;
}
- (NSData*) decryptedDataUsingAESKey: (NSData *) key {
const uint8_t * p = [self bytes];
size_t length = [self length];
if (length
1
kCCParamError
is, as its name says, an error. Why are you treating it as success? If you get that error, it means you did something wrong; look at the parameters you passed and figure out what.
正如其名,kCCParamError是一个错误。你为什么把它当作成功?如果你犯了这个错误,就意味着你做错了什么;看看你传递的参数并找出其中的原因。
This is probably why you're getting “garbage”: CCCrypt
(decrypting) never actually gave you anything, because it could not work with whatever values you gave it. What you're getting is whatever was lying around in the output buffer when you allocated it.
这可能就是你得到“垃圾”的原因:CCCrypt(解密)从来没有给过你任何东西,因为它不能与你提供的任何值一起工作。你得到的是当你分配它的时候在输出缓冲区里的任何东西。
If you switch to calloc
or to creating the NSMutableData object before calling CCCrypt
and using its mutableBytes
as the buffer, I think you'll find that the buffer then always contains all zeroes. Same reason: CCCrypt
is not filling it out, because it's failing, because you passed one or more wrong values (parameter error).
如果切换到calloc或在调用CCCrypt之前创建NSMutableData对象,并使用其mutableBytes作为缓冲区,我想你会发现缓冲区总是包含所有的零。同样的原因:CCCrypt没有填充它,因为它失败了,因为您传递了一个或多个错误的值(参数错误)。
You need to fix the parameter error before you can expect this to work.
您需要修正参数错误,然后才能期望它工作。
You might try breaking the CCCrypt
call into calls to CCCryptorCreate
, CCCryptorUpdate
, CCCryptorFinal
, and CCCryptorRelease
, at least temporarily, to see where it's going wrong.
您可能会尝试将CCCrypt调用分解为对CCCryptorCreate、CCCryptorUpdate、CCCryptorFinal和CCCryptorRelease的调用,至少是暂时的,看看哪里出错了。
Is your encryption method returning YES
or NO
? I'm guessing it returns NO
, because the code appears to be mostly the same between the encryption and decryption methods, so whatever you have wrong in your decryption code is probably wrong in your encryption code as well. See what CCCrypt
is returning and, if it's failing, get it working.
您的加密方法是否返回YES或NO?我猜它会返回NO,因为代码在加密和解密方法之间几乎是相同的,所以在你的解密代码中任何错误都可能在你的加密代码中是错误的。看看CCCrypt返回了什么,如果失败了,让它工作。
If it is returning YES
(CCCrypt
is succeeding), then I wonder what you mean by “returns me a bunch of garbage”. Are you referring to the contents of the data object you sent the encryptWithAES128Key:
message to?
如果它返回YES (CCCrypt正在成功),那么我想知道您的意思是什么“返回一堆垃圾”。您是指您发送的encryptWithAES128Key:消息到的数据对象的内容吗?
If that's the case, then that is the expected result. Your code encrypts the contents of the data object in place, overwriting the cleartext with the ciphertext. What you're seeing isn't pure “garbage”—it's the ciphertext! Decrypting it (successfully) will reveal the cleartext again.
如果是这样的话,那就是预期的结果。您的代码对数据对象的内容进行加密,以密文覆盖明文。你看到的不是纯粹的“垃圾”,而是密文!解密(成功)将再次显示明文。
By the way, you have the “encrypts in-place, since this is a mutable data object” comment on the creation of an output buffer in order to not work in-place in the decryption code. It should be in the encryption method, where you are working in-place. I suggest making either both work in-place or neither work in-place; consistency is a virtue.
顺便说一下,您有“就地加密,因为这是一个可变的数据对象”对输出缓冲区的创建进行注释,以便在解密代码中不工作。它应该在加密方法中,在那里你正在工作。我建议要么在工作中要么在原地工作,要么不工作;一致性是一种美德。
0
If you have following padding changes in your code remove it and always keep kCCOptionPKCS7Padding on, this should solve your issue.
如果您在代码中有以下修改,请删除它,并始终保持kCCOptionPKCS7Padding,这将解决您的问题。
if (encryptOrDecrypt == kCCEncrypt) {
if (*pkcs7 != kCCOptionECBMode) {
if ((plainTextBufferSize % kChosenCipherBlockSize) == 0) {
*pkcs7 = 0x0000;
} else {
*pkcs7 = kCCOptionPKCS7Padding;
}
}
}
0
You should use RNCryptor, it's high level encryption opensource api around CommonCrypto, and high level encryption API's are the best practice for cryptography these days, because it's easy for experts to make mistakes in the implementations using crypto primatives, and there are alot of side channel attacks out there that take advantage of those mistakes.
您应该使用RNCryptor,高度加密CommonCrypto开源api,和高级加密api是密码学的最佳实践这些天,因为专家犯错很容易实现使用加密原语,还有很多的侧信道攻击利用这些错误。
For example, you code says /* initialization vector (optional) * /
100% not true, thus you've totally crippled AES-CBC, and that's just the most obvious issue.
例如,您的代码说/*初始化向量(可选)* / 100%不正确,因此您完全瘫痪了AES-CBC,这是最明显的问题。
In your case RNCryptor is ideal, I'd strongly suggest you don't roll your own implementation.
在您的情况下,RNCryptor是理想的,我强烈建议您不要执行自己的实现。