【问题标题】:How to AES-GCM for iOS and Android如何为 iOS 和 Android 进行 AES-GCM
【发布时间】:2017-06-06 08:14:33
【问题描述】:

我想创建带有身份验证标签的 AES 加密和解密 GCM 模式。 这是我的iOS版本源代码:

CCCryptorStatus ccStatus = kCCSuccess;
NSData *iv = [hexIV dataUsingEncoding:NSUTF8StringEncoding];
NSData *symmetricKey = [hexIV dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData  *dataOut = [NSMutableData dataWithLength:self.length];
NSMutableData  *tag = [NSMutableData dataWithLength:kCCBlockSizeAES128];
size_t          tagLength = kCCBlockSizeAES128;

ccStatus = CCCryptorGCM(kCCEncrypt,
                        kCCAlgorithmAES,
                        symmetricKey.bytes,
                        kCCKeySizeAES256,
                        iv.bytes,
                        iv.length,
                        aad.bytes,
                        aad.length,
                        self.bytes,
                        self.length,
                        dataOut.mutableBytes,
                        tag.bytes,
                        &tagLength);

if (ccStatus == kCCSuccess) {
    return [NSDictionary dictionaryWithObjectsAndKeys:dataOut,@"cyphertext",tag,@"tag",iv,@"iv",nil];
} else {
    return nil;
}

我想将此代码更改为Android版本,在Android的源代码下方:

byte[] aKey = hexStringToByteArray(hexKey);
byte[] aIV = hexStringToByteArray(hexIV);
Key key = new SecretKeySpec(aKey, "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(16 * Byte.SIZE, aIV));
cipher.updateAAD(aad);
byte[] encrypted = cipher.doFinal(aKey);

如何在我的源代码中添加认证标签?

【问题讨论】:

    标签: android ios encryption aes-gcm


    【解决方案1】:

    当我在 iOS 中加密 AES GCM 时

    let iv = AES.GCM.Nonce()
    let sealedBox = try! AES.GCM.seal(rawJsonData, 
                                      using: yourKey, 
                                      nonce: yourIv)
    let cipher = sealedBox.ciphertext + sealedBox.tag
    

    记住,在 android 中你有:IV + Cipher + Tag

    你可以很容易地在 iOS 中重现这个来解密,遵循相同的结构,

    let incomingCipher = (payload?.fromBase64())!
    let IV = initialVector?.fromBase64()
    let combine = IV! + incomingCipher
    let myNewSealedBox = try AES.GCM.SealedBox(combined: combine)
    

    incomingCipher (Android) 包含 cipher + Tag

    【讨论】:

      猜你喜欢
      • 2016-04-23
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      相关资源
      最近更新 更多