[英]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.