我的java和Objective c加密方法产生不同的输出 - AES128,CBC模式。
键:YnA+lracf9xaiJO1oA/bTQ==
iV:190Dt3MNeL32o9Kd37HZlQ==
纯文本:text to encrypt
Java输出:mHZpz52LOK2K76t3B/EUuA==
Obj C输出:Fb0D46H4tN+ukgI05x/Dbg==
Java代码:
public static String AESEncrypt(String text, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes = new byte[16];
byte[] b = key.getBytes("UTF-8");
int len = b.length;
if (len > keyBytes.length)
len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
byte[] keyBytesiv = new byte[16];
byte[] biv = iv.getBytes("UTF-8");
int leniv = biv.length;
if (leniv > keyBytesiv.length)
leniv = keyBytesiv.length;
System.arraycopy(biv, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytesiv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(results);
}
目标C代码
+ (NSData *)AESOperation:(CCOperation)operation OnData:(NSData *)data key:(NSData *)key iV:(NSData *) iv {
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
[key bytes],
kCCBlockSizeAES128,
[iv bytes],
[data bytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
答案 0 :(得分:4)
这样的问题有两种方法可以合并:
作为完整性检查,请尝试使用两种语言解密加密文本并查看其是否与原始文本匹配。
尝试使用其他库(第三个库)并与前两个值进行比较。
所以我尝试使用在线工具解密密文,并且可以使用Objective C输出恢复原始文本("要加密的文本")。它表明Java代码存在问题。我怀疑它可能与输入(key,iv)是base64编码的事实有关,而它似乎只是被视为UTF-8编码(getBytes()
调用)。
答案 1 :(得分:0)
由于上面的建议,我能够解决java代码的问题。下面是Java代码,它可以帮助我在java和Objective c上实现AES128 CBC模式
public static String AESEncrypt(String text, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes = new byte[16];
byte[] b = new BASE64Decoder().decodeBuffer(key);
int len = b.length;
if (len > keyBytes.length)
len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
byte[] keyBytesiv = new byte[16];
byte[] biv = new BASE64Decoder().decodeBuffer(iv);
int leniv = biv.length;
if (leniv > keyBytesiv.length)
leniv = keyBytesiv.length;
System.arraycopy(biv, 0, keyBytesiv, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytesiv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(results);
}