java-python aes-gcm 加密說明

python-java 的 AES-GCM 加解說明

內(nèi)容

  1. 說明
  2. 測試數(shù)據(jù)
  3. python-PyCryptodome版本
  4. python-cryptography版本
  5. java版本

說明

  1. AES-GCM是一種NIST標準的認證加密算法, 是一種能夠同時保證數(shù)據(jù)的保密性、 完整性和真實性的一種加密模式。它最廣泛的應(yīng)用是在TLS中。
  2. GCM詳細說明
測試數(shù)據(jù)
AES加密模式:AEAD_AES_256_GCM

AES密鑰:
aesKey = 1d35eefc2b8207d615028d056ce5296c
附加數(shù)據(jù):
associatedData = 12345
隨機數(shù)據(jù):nonceData
nonceData = 1234567812345678
數(shù)據(jù)明文: 1234561234565
數(shù)據(jù)密文:X3lkQaqdASpIF0+XsOjwUhfCZdvXh3RQFXsH8o8=

python demo--PyCryptodome版本
import base64
from Crypto.Cipher import AES

aes_key = '1d35eefc2b8207d615028d056ce5296c'
associatedData = "12345"
nonce = "1234567812345678"

def aes_en_gcm_func():
    de_data = '1234561234565'
    cipher = AES.new(aes_key.encode(), AES.MODE_GCM, nonce=nonce.encode())
    cipher.update(associatedData.encode())
    ct, tag = cipher.encrypt_and_digest(de_data.encode('utf-8'))
    return base64.b64encode(ct + tag).decode('utf-8')


def aes_de_gcm_func():
    en_data = 'X3lkQaqdASpIF0+XsOjwUhfCZdvXh3RQFXsH8o8='
    cipher = AES.new(aes_key.encode(), AES.MODE_GCM, nonce=nonce.encode())
    cipher.update(associatedData.encode())
    en_data = base64.b64decode(en_data.encode('utf-8'))
    auth_tag = en_data[-16:]
    _en_data = en_data[:-16]
    plaintext = cipher.decrypt_and_verify(_en_data, auth_tag)
    return plaintext.decode()
python demo--cryptography 版本
import base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

aes_key = '1d35eefc2b8207d615028d056ce5296c'
associatedData = "12345"
nonce = "1234567812345678"

def st_aes_en_func():
    de_data = '1234561234565'
    aesgcm = AESGCM(aes_key.encode())
    ct = aesgcm.encrypt(nonce.encode(), de_data.encode(), associatedData.encode())
    return base64.b64encode(ct).decode('utf-8')


def st_aes_de_func():
    en_data = 'X3lkQaqdASpIF0+XsOjwUhfCZdvXh3RQFXsH8o8='
    en_data = base64.b64decode(en_data.encode('utf-8'))
    aesgcm = AESGCM(aes_key.encode())
    ct = aesgcm.decrypt(nonce.encode(), en_data, associatedData.encode())
    return ct.decode()
java demo
package tools;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AesUtil {
    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;
    private final byte[] aesKey;

    public AesUtil(byte[] key) {
        if (key.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("無效的ApiV3Key,長度必須為32個字節(jié)");
        }
        this.aesKey = key;
    }

    public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
            throws GeneralSecurityException, IOException {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);

            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData);

            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public String encryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
            throws GeneralSecurityException, IOException{
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);

            cipher.init(Cipher.ENCRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData);

//            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
            return new String(Base64.getEncoder().encode(cipher.doFinal(ciphertext.getBytes())), "utf-8");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }
    public static void main(String[] args) throws Exception {
        String key = "1d35eefc2b8207d615028d056ce5296c";
        String associatedData = "12345";
        String nonce = "1234567812345678";
        AesUtil aesUtils = new AesUtil(key.getBytes());

        String enData = aesUtils.encryptToString(associatedData.getBytes(), nonce.getBytes(), "1234561234565");
        System.out.println("加密后密文:" + enData);
        String deData = aesUtils.decryptToString(associatedData.getBytes(), nonce.getBytes(), enData);
        System.out.println("解密后明文:" + deData);

    }

}


  • 參考
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本人在java中運行的一段AES加密代碼,采用的是GCM加密模式,出于某種原因需要將這部分代碼移植到python項...
    Halis_123閱讀 6,695評論 3 2
  • AES是一種對稱加密算法,可以參考:https://blog.csdn.net/qq_28205153/artic...
    阿幫I3閱讀 3,543評論 0 3
  • 本篇主要介紹筆者在iOS開發(fā)工作中用到的加解密算法的使用,主要包括:1)對稱加密算法:AES、DES、3DES2)...
    江山風(fēng)雨閱讀 5,264評論 1 5
  • 以太坊Whisper協(xié)議中,默認的對稱加密使用的是AES-GCM加密算法。 AES是一種對稱加密算法,它的相關(guān)概念...
    叫我null閱讀 1,916評論 0 1
  • window下安裝 1.安裝python 下載python-3.7.0-amd64.exe,直接下一步安裝,記得勾...
    Creator_Ly閱讀 1,269評論 0 0

友情鏈接更多精彩內(nèi)容