Aes生成key和iv,加密解密

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;


/**
 * Created with IntelliJ IDEA.
 *
 * @author : Future master
 * @version : 1.0
 * @Project : C4
 * @Package : org.example
 * @ClassName : Aes.java
 * @createTime : 2021/11/26 18:05
 */
public class Aes {
    private String Key;
    private String Iv;
    private static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
    private static final String AES = "AES";
    //构造函数进行初始化key和iv(随机生成)
    public Aes(){
        this.Key = getRandom(16);
        this.Iv = getRandom(16);
    }
    public String getKey(){
        return this.Key;
    }
    public String getIv(){
        return this.Iv;
    }
    public String getRandom(int length){
        char[] arr = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k',
                'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        String result = String.valueOf(arr[(int)Math.floor(Math.random()*36)]);
        for(int i = 1;i<length;i++){
            result+=arr[(int)Math.floor(Math.random()*36)];
        }
        return result;
    }
    //进行加密返回一个byte[]
    public byte[] encrypt(String content){
        byte[] result = null;
        byte[] keyCode = Key.getBytes(StandardCharsets.UTF_8);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
            IvParameterSpec zeroIv = new IvParameterSpec(Iv.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec skeySpec = new SecretKeySpec(keyCode,AES);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, zeroIv);// 初始化为加密模式的密码器
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
        try {
            result = cipher.doFinal(byteContent);// 加密
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return result;
    }
    //进行解密返回一个String
    public static final String decrypt(byte[] bytes,String key,String iv){
        String result = null;
        byte[] byteIv = iv.getBytes(StandardCharsets.UTF_8);
        byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);
        IvParameterSpec myIv = new IvParameterSpec(byteIv);
        SecretKeySpec myKey = new SecretKeySpec(byteKey,AES);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
            cipher.init(Cipher.DECRYPT_MODE, myKey, myIv);// 初始化
            byte[] result1 = cipher.doFinal(bytes);
            result = new String(result1,0,result1.length);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid);
        System.out.println(uuid.toString().replaceAll("-", ""));
        Aes aes = new Aes();
        System.out.println(aes.getKey());
        System.out.println(aes.getIv());

        byte[] miwen = aes.encrypt("测试一下");
        System.out.println(miwen);
        String decrypt = Aes.decrypt(miwen, aes.Key, aes.Iv);
        System.out.println(decrypt);
    }
}

import java.nio.charset.StandardCharsets;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

public class AESUtils {
    public AESUtils() {
    }

    public static String decrypt(byte[] secretBytes, String secretKey) throws Exception {
        if (secretKey.length() != 16) {
            throw new RuntimeException("key length must be 16 for AES");
        } else {
            SecretKey key = new SecretKeySpec(secretKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(key.getAlgorithm());
            cipher.init(2, key);
            return new String(cipher.doFinal(secretBytes), StandardCharsets.UTF_8);
        }
    }

    public static byte[] encrypt(String simple, String secretKey) throws Exception {
        if (secretKey.length() != 16) {
            throw new RuntimeException("key length must be 16 for AES");
        } else {
            SecretKey key = new SecretKeySpec(secretKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(key.getAlgorithm());
            cipher.init(1, key);
            return cipher.doFinal(simple.getBytes(StandardCharsets.UTF_8));
        }
    }

    /** @deprecated */
    public static String encryptData(String key, String iv, String content) throws Exception {
        byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(1, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(byteContent);
        return Base64.encodeBase64String(encryptedBytes);
    }

    /** @deprecated */
    public static String decryptData(String key, String iv, String content) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(2, secretKey, ivParameterSpec);
        byte[] encryptedBytes = Base64.decodeBase64(content);
        byte[] result = cipher.doFinal(encryptedBytes);
        return new String(result, StandardCharsets.UTF_8);
    }

    public static String encryptToBase64(String key, String iv, String content) throws Exception {
        byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(1, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(byteContent);
        return Base64.encodeBase64String(encryptedBytes);
    }

    public static String decryptFromBase64(String key, String iv, String base64Str) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(2, secretKey, ivParameterSpec);
        byte[] encryptedBytes = Base64.decodeBase64(base64Str);
        byte[] result = cipher.doFinal(encryptedBytes);
        return new String(result, StandardCharsets.UTF_8);
    }

    public static String encryptToHex(String key, String iv, String content) throws Exception {
        byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(1, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(byteContent);
        return Hex.encodeHexString(encryptedBytes);
    }

    public static String decryptFromHex(String key, String iv, String hexStr) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(2, secretKey, ivParameterSpec);
        byte[] result = cipher.doFinal(Hex.decodeHex(hexStr));
        return new String(result, StandardCharsets.UTF_8);
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的uniapp中使用AES加密和解密的示例代码: ```javascript // 加密 function encryptData(data, key, iv) { const cipher = uniCrypto.createCipheriv('aes-128-cbc', key, iv) let encrypted = cipher.update(data, 'utf8', 'base64') encrypted += cipher.final('base64') return encrypted } // 解密 function decryptData(data, key, iv) { const decipher = uniCrypto.createDecipheriv('aes-128-cbc', key, iv) let decrypted = decipher.update(data, 'base64', 'utf8') decrypted += decipher.final('utf8') return decrypted } // 使用示例 const data = 'Hello World!' const key = '1234567812345678' const iv = '8765432187654321' const encrypted = encryptData(data, key, iv) console.log('加密后的数据:', encrypted) const decrypted = decryptData(encrypted, key, iv) console.log('解密后的数据:', decrypted) ``` 在上面的代码中,`encryptData`函数接收要加密的数据、加密密钥和初始化向量(iv),并使用`uniCrypto.createCipheriv`方法创建一个AES加密器,然后使用`cipher.update`和`cipher.final`方法进行加密,最后返回加密后的数据。 `decryptData`函数接收要解密的数据、解密密钥和初始化向量(iv),并使用`uniCrypto.createDecipheriv`方法创建一个AES解密器,然后使用`decipher.update`和`decipher.final`方法进行解密,最后返回解密后的数据。 在使用时,只需将要加密的数据、加密密钥和初始化向量(iv)传递给`encryptData`函数即可获得加密后的数据,将加密后的数据、解密密钥和初始化向量(iv)传递给`decryptData`函数即可获得解密后的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值