在iOS和Android中使用AES加密/解密

时间:2013-04-05 08:15:19

标签: android ios aes

我想用iOS和Android加密相同的文字:“Lorem ipsum dolor sit amet”。

使用的密钥是:“A01BD1BE-9D28-11E2-A12E-48086188709B”

iOS实施:

- (NSData *)AES256EncryptWithKey:(NSString *)key{


char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)

// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

//See 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 bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesEncrypted );
if( cryptStatus == kCCSuccess )
{
    //the returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}

free( buffer ); //free the buffer
return nil;}

Android实施:

byte[] rawKey = new byte[32];

System.arraycopy("A01BD1BE-9D28-11E2-A12E-48086188709B".getBytes("UTF-8"), 0, rawKey, 0, 32);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

final byte[] iv = new byte[16];
Arrays.fill(iv, (byte) 0x00);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
SecretKeySpec keySpec = new SecretKeySpec(rawKey, "AES");

cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] results = cipher.doFinal(clearTextByte);
String result = Base64.encodeToString(results, Base64.DEFAULT);

我得到了不同的结果。

为什么?

0 个答案:

没有答案