AES --加密

2022/5/1 6:14:51

本文主要是介绍AES --加密,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

java的AES加密:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Arrays;


public class Hello {
    public static void main(String[] args) {
        String name = "哈喽啊";

        //设置AES加密的 key 和 iv
        String key = "fehg123hjj216jjwqhe16i32kj1nkn22";//key必需是32位
        String iv = "77b07a672d57d643"; // iv 必须是16位

        //加密
        byte[] raw = key.getBytes();
        SecretKeySpec secretKey = new SecretKeySpec(raw,"AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,secretKey,ivSpec);
            byte[] encrypted = cipher.doFinal(name.getBytes());

            System.out.println(Arrays.toString(encrypted));
        }catch (Exception e){
        System.out.println(e);
        }
    }
    }

python的AEC加密:

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

KEY= "fehg123hjj216jjwqhe16i32kj1nknnw"
IV ="77b07a672d57d64c"

def aes_encrypt(data_string):
    aes = AES.new(
        key = KEY.encode('utf-8'),
        mode = AES.MODE_CBC,
        iv = IV.encode('utf-8'),
    )
    raw = pad(data_string.encode("utf-8"),16)
    return aes.encrypt(raw)

data = aes_encrypt("哈喽啊")

#将字节类型转成到16进制表示
c = data.hex()
print(c) #打印结果:f30a976c22f42dbd7d6bf26fe2c84cc9
print(data) # 打印结果(字节类型): b'\xf3\n\x97l"\xf4-\xbd}k\xf2o\xe2\xc8L\xc9'
print([i for i in data]) #打印结果(每个字节的ASCII码):[243, 10, 151, 108, 34, 244, 45, 189, 125, 107, 242, 111, 226, 200, 76, 201]


这篇关于AES --加密的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程