AES加密java端实现

在使用RSA完成敏感信息获取AES钥匙后,我们需要对数据传输进行AES加密,话不多说上AES核心加密代码。如需要Spring框架或者Netty框架的配置及使用,私聊联系我

1.代码

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Base64;
import java.util.Random;

public class AESEncrypt {

    static {
        //如果是PKCS7Padding填充方式,则必须加上下面这行(为保证前后端一致性建议使用PKCS7Padding方式,也可以使用PKCS5Padding则可以不加)
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 创建Key
     * @return aesKey
     */
    public static String initKey(){
        String str="yzABcdCfgDqrEvwFGpsHIoxJKtuLhiMejNOklPQmnRSabTUX01VW23456YZ789";
        Random random=new Random();
        StringBuilder sb=new StringBuilder();
        while (sb.length()<16) sb.append(str.charAt(random.nextInt(str.length())));
        return sb.toString();
    }

    /**
     * AES加密
     * @param plaintext 目标文字
     * @param aesKey 密码
     * @return 结果
     */
    public static String encrypt(String plaintext, String aesKey) {
        try {
            SecretKeySpec sKeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
            byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.getEncoder().encode(encrypted));
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * AES解密
     * @param cipherText 密文
     * @param aesKey   密钥
     * @return 明文
     */
    public static String decrypt(String cipherText, String aesKey) {
        try {
            SecretKeySpec sKeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
            byte[] encrypted = Base64.getDecoder().decode(cipherText); //先用base64解密
            return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 进行MD5加密
     * @param text 要进行MD5转换的字符串
     * @return 该字符串的MD5值
     */
    public static String MD5(String text) throws NoSuchAlgorithmException {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = text.getBytes();
        MessageDigest mdInst = MessageDigest.getInstance("MD5");
        mdInst.update(btInput);
        byte[] md = mdInst.digest();
        int j = md.length;
        char[] str = new char[j * 2];
        int k = 0;
        for (byte byte0 : md) {
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }
}

ok,到此我们就完成了一个核心的后端加密。

2.前端对应代码

前端分NPM和脚本直接引入。我这里就简单分享下脚本引入方式,如需NPM请私聊联系我(最好是妹子)。

  1. 引入cipher.min.js脚本,提取码:api2
var encData = aesEncrypt("12345","password");
var plainText = aesDecrypt("ttt==","password");
var rasEnc = rsaEncrypt("laks","publicKey");
var initAesKey = initAesKey();

OK,大功告成

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java实现AES加密的代码示例: 1. 导入相关包 ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; ``` 2. 定义加密方法 ```java public static String encrypt(String input, String key) throws Exception { byte[] inputBytes = input.getBytes("UTF-8"); // 16字节密钥 byte[] keyBytes = key.getBytes("UTF-8"); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); // ECB模式 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] encrypted = cipher.doFinal(inputBytes); // 转换为Base64编码 return Base64.getEncoder().encodeToString(encrypted); } ``` 3. 定义解密方法 ```java public static String decrypt(String encryptedInput, String key) throws Exception { // 解码Base64 byte[] encryptedBytes = Base64.getDecoder().decode(encryptedInput); // 16字节密钥 byte[] keyBytes = key.getBytes("UTF-8"); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); // ECB模式 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decrypted = cipher.doFinal(encryptedBytes); return new String(decrypted, "UTF-8"); } ``` 4. 示例使用 ```java public static void main(String[] args) throws Exception { String input = "Hello World"; String key = "0123456789abcdef"; // 加密 String encrypted = encrypt(input, key); System.out.println("Encrypted: " + encrypted); // 解密 String decrypted = decrypt(encrypted, key); System.out.println("Decrypted: " + decrypted); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值