[英]iOS symmetric key encryption / decryption equivalent to Java
我正在尝试将ios的数据ios加密/解密,而将ios的java的数据加密/解密
- (NSData *) encrypt:(NSData *) dataToEncrypt symmetricKey:(NSData *)symmetricKey context:(CCOperation)encryptOrDecrypt{
NSUInteger data_length= [dataToEncrypt length];
uint8_t input_raw_data[data_length];
//The [dataToEncrypt length] gives the number of chars present in the string.So say there are 10 chars.
//Now,the getBytes needs to get the raw bytes from this i.e. binary NSData.But suppose the encoding was
//full 16 bit encoding then the number of bytes needed wd have been double- 20.But as we are using the
//NSUTF8StringEncoding,the number of byes needed is 1 per char as the chars(even if originally unicode are
//compressed into an 8 bit UTF8 encoding.)
[dataToEncrypt getBytes:&input_raw_data length:data_length];
// [dataToEncrypt getBytes:&input_raw_data maxLength:data_length usedLength:NULL encoding:NSUTF8StringEncoding options:0 range:NSMakeRange(0,data_length) remainingRange:NULL];
//According to the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t buffer_size = data_length + kCCBlockSizeAES128;
void* buffer = malloc(buffer_size);
size_t num_bytes_encrypted = 0;
CCCryptorStatus crypt_status = CCCrypt(encryptOrDecrypt, kCCAlgorithmAES128, 0x0000,
[symmetricKey bytes], kCCKeySizeAES128,
NULL,
input_raw_data, data_length,
buffer, buffer_size,
&num_bytes_encrypted);
// NSLog(@"~~num bytes encrypted: %d",num_bytes_encrypted);
if (crypt_status == kCCSuccess){
NSLog(@"~~Data encoded successfully...");
return [NSData dataWithBytesNoCopy:buffer length:num_bytes_encrypted];
}
free(buffer); //free the buffer;
return nil;
}
Java代码-
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
String keyString = "keykeykeykeykeykeykeykey";
byte[] keyBytes = keyString.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(new byte[16]));
byte[] resultBytes = cipher.doFinal("Hallo Welt!".getBytes("UTF8"));
FileOutputStream out = new FileOutputStream(new File("encryptedFileJava"));
out.write(resultBytes); out.close();
这是加密的文本-“ Seább| 8” R,
键-BW3dKDf2bkDC4Bq9xTdr1g ==
请帮助我或建议我任何解决方案。
谢谢。
您至少有两个问题:
Objective C代码使用ECB模式,而Java代码使用CBC模式。 在CCrypt调用中使用零而不是NULL的字节数组来使用IV值为零的CBC模式(如Java代码)。
由于keyBytes为24个字节长,因此Java将使用AES-192。 CCrypt只会忽略多余的字节。 将AES-192指定为CCrypt或使用128位密钥(“ keykeykeykeykeyk”应该起作用)。
为了在IOS和Java设备之间进行安全通信,可以使用对称密钥加密。
在平台不同的情况下,建议生成的密钥是纯文本密钥,而不是API生成的密钥。
在这种情况下,可以使用AES 128位加密。 IOS设备能够生成对称密钥并使用AES加密来加密文本。
以下链接提供了使用纯文本对称密钥进行加密和解密的Java代码
http://www.java-redefined.com/2015/06/symmetric-key-encryption-ios-java.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.