我正在使用 CommonCrypto CCCryptorCreate 来解密消息。我正在使用密码和 IV,但它总是返回 nil。
如果我使用 CCCryptorCreate 进行解密,但在 RUBY 端加密期间不使用 IV 并且不在 obj-c 解密端使用 IV,则解密工作完美,我可以看到消息。
但是,如果我在 RUBY 上使用 IV 并在 obj-c 端使用 IV,则解密以 nil 消息对象结束。
我在Objective-C中使用这个加密/在Ruby中使用任何东西解密
OBJ-C方法:
- (NSData *) decryptedDataUsingAlgorithm: (CCAlgorithm) algorithm
key: (id) key // data or string
initializationVector: (id) iv // data or string
options: (CCOptions) options
error: (CCCryptorStatus *) error
{
CCCryptorRef cryptor = NULL;
CCCryptorStatus status = kCCSuccess;
NSParameterAssert([key isKindOfClass: [NSData class]] || [key isKindOfClass: [NSString class]]);
NSParameterAssert(iv == nil || [iv isKindOfClass: [NSData class]] || [iv isKindOfClass: [NSString class]]);
NSMutableData * keyData, * ivData;
if ( [key isKindOfClass: [NSData class]] )
keyData = (NSMutableData *) [key mutableCopy];
else
keyData = [[key dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
if ( [iv isKindOfClass: [NSString class]] )
ivData = [[iv dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
else
ivData = (NSMutableData *) [iv mutableCopy]; // data or nil
#if !__has_feature(objc_arc)
[keyData autorelease];
[ivData autorelease];
#endif
// ensure correct lengths for key and iv data, based on algorithms
FixKeyLengths( algorithm, keyData, ivData );
status = CCCryptorCreate( kCCDecrypt, algorithm, options,
[keyData bytes], [keyData length], [ivData bytes],
&cryptor );
if ( status != kCCSuccess )
{
if ( error != NULL )
*error = status;
return ( nil );
}
NSData * result = [self _runCryptor: cryptor result: &status];
if ( (result == nil) && (error != NULL) )
*error = status;
CCCryptorRelease( cryptor );
return ( result );
}
=== DOES NOT WORK ====
NSData * result = [self decryptedDataUsingAlgorithm: kCCAlgorithmAES128
key: [[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash]
initializationVector: [anIV dataUsingEncoding:NSUTF8StringEncoding]
options: kCCOptionPKCS7Padding
error: &status];
=== DOES WORK ===
NSData * result = [self decryptedDataUsingAlgorithm: kCCAlgorithmAES128
key: [[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash]
initializationVector: nil
options: kCCOptionPKCS7Padding
error: &status];