【发布时间】:2015-02-24 07:02:45
【问题描述】:
我正在使用 AES 加密算法 (ECB) 并使用 ASI http 库,但由于 401 未经授权,我的请求失败。 我在下面附上了我的代码。
加密算法。(AES 128 加密)
+ (NSData*)encryptData:(NSData*)data key:(NSData*)key iv:(NSData*)iv;
{
NSData* result = nil;
// setup key
unsigned char cKey[FBENCRYPT_KEY_SIZE];
bzero(cKey, sizeof(cKey));
[key getBytes:cKey length:FBENCRYPT_KEY_SIZE];
// setup iv
char cIv[FBENCRYPT_BLOCK_SIZE];
bzero(cIv, FBENCRYPT_BLOCK_SIZE);
if (iv) {
[iv getBytes:cIv length:FBENCRYPT_BLOCK_SIZE];
}
// setup output buffer
size_t bufferSize = [data length] + FBENCRYPT_BLOCK_SIZE;
void *buffer = malloc(bufferSize);
// do encrypt
size_t encryptedSize = 0;
// / CCCryptorStatus cryptStatus2 = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, [data bytes], [data length], NULL, [cipherData bytes], outLength, [decodedData mutableBytes], [decodedData length], &outLength);
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
FBENCRYPT_ALGORITHM,
kCCOptionPKCS7Padding | kCCOptionECBMode,
cKey,
FBENCRYPT_KEY_SIZE,
cIv,
[data bytes],
[data length],
buffer,
bufferSize,
&encryptedSize);
if (cryptStatus == kCCSuccess) {
result = [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
} else {
free(buffer);
NSLog(@"[ERROR] failed to encrypt|CCCryptoStatus: %d", cryptStatus);
}
return result;
}
解密算法。(AES 128 解密)
+ (NSData*)decryptData:(NSData*)data key:(NSData*)key iv:(NSData*)iv;
{
NSData* result = nil;
// setup key
unsigned char cKey[FBENCRYPT_KEY_SIZE];
bzero(cKey, sizeof(cKey));
[key getBytes:cKey length:FBENCRYPT_KEY_SIZE];
// setup iv
char cIv[FBENCRYPT_BLOCK_SIZE];
bzero(cIv, FBENCRYPT_BLOCK_SIZE);
if (iv) {
[iv getBytes:cIv length:FBENCRYPT_BLOCK_SIZE];
}
// setup output buffer
size_t bufferSize = [data length] + FBENCRYPT_BLOCK_SIZE;
void *buffer = malloc(bufferSize);
// do decrypt
size_t decryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
FBENCRYPT_ALGORITHM,
kCCOptionECBMode,
cKey,
FBENCRYPT_KEY_SIZE,
cIv,
[data bytes],
[data length],
buffer,
bufferSize,
&decryptedSize);
if (cryptStatus == kCCSuccess) {
result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize];
} else {
free(buffer);
NSLog(@"[ERROR] failed to decrypt| CCCryptoStatus: %d", cryptStatus);
}
return result;
}
Base 64 算法。
- (NSString *)base64EncodedString
{
size_t outputLength;
char *outputBuffer =
NewBase64Encode([self bytes], [self length], true, &outputLength);
NSString *result =
[[[NSString alloc]
initWithBytes:outputBuffer
length:outputLength
encoding:NSASCIIStringEncoding]
autorelease];
free(outputBuffer);
return result;
}
请做必要的事。 提前致谢
【问题讨论】:
-
是什么让您认为问题在于加密?密钥、数据输入和输出的十六进制转储在哪里? ECB 确实不安全,尤其是对于图像,但有设置 iv 的代码。即使作者建议不要使用 ASI,您为什么还要使用它,AFNetworking 是最新的并且正在积极维护中。为什么使用 Apple 提供的第 3 方 Base64 代码?你为什么不使用 ARC?
-
我想大部分问题都可以通过选择第 3 方项目来回答,选择更好、更当前的项目。 RNCryptor 是最新的,可能适合您的需求。
-
感谢您的回复,但是已经在 php 端实现了 ECB,所以我不能使用 CBC,否则 php 服务器无法解密我的请求。
-
由于 unicodes 我的请求失败了,是否有任何替代方案可以为 RNCryptor 实施 ECB?
-
加密是基于数据的,您将字符串转换为数据并加密/解密数据,然后再转换回所需的任何格式。
标签: ios objective-c iphone encryption aes