AES加密之ECB-JAVA实现

这是一个Java编写的AESUtil工具类,主要实现了AES算法的ECB模式加密和解密功能,使用了PKCS5Padding填充方式。类中包含生成AES密钥、Base64编码和解码的方法,可用于学习和实际项目中。
摘要由CSDN通过智能技术生成
package com.simple.tool.signcheck.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


public class AESUtil {

    private static final String DATA_ENCODING = "UTF-8";

    private static final int KEY_SIZE = 128;

    //AES DES
    private static final String ALGORITHM = "AES";

    /**
     * AES/ECB/PKCS5Padding    DES/CBC/PKCS5Padding
     */
    private static final String ALGORITHM_PATTERN = "AES/ECB/PKCS5Padding";

    public static String encrypt(String data, String key) throws Exception {
        return encrypt(data, key.getBytes("UTF-8"));
    }

    public static String decrypt(String data, String key) throws Exception {
        return decrypt(data, key.getBytes("UTF-8"));
    }
    
    /**
     * base64 encode
     * @param key
     * @return
     * @throws Exception
     */
    public static String encodeBase64String(String key) throws Exception {
        return Base64Util.encode(key.getBytes(DATA_ENCODING));
    }
    

    public static String generateAESKeyStr() throws Exception {
        byte[] key = generateAESKey(0);
        return Base64Util.encode(key);
    }

    public static void main(String[] args) throws Exception {

    	String str = "123456";
    	String key = "1234567890121234";
    	String result = AESUtil.encrypt(str, key);
    	System.out.println(result);
    	
    	String rr = AESUtil.decrypt("j6ziIPht1g3yrTw9gDGCAg==", key);
    	System.out.println(rr);

    }

    private static byte[] generateAESKey(int keySize) throws Exception {
        byte[] key = (byte[]) null;
        KeyGenerator kgen = null;
        if (keySize != KEY_SIZE) {
            keySize = KEY_SIZE;
        }
        try {
            kgen = KeyGenerator.getInstance(ALGORITHM);
            kgen.init(keySize);
            SecretKey skey = kgen.generateKey();
            key = skey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("ִAES算法异常", e);
        }
        return key;
    }

    public static String generateAESKey(String keyStr) throws Exception {
        byte[] key = generateAESKey(keyStr, KEY_SIZE);
        return Base64Util.encode(key);
    }

    private static byte[] generateAESKey(String keyStr, int keySize) throws Exception {

        byte[] key = (byte[]) null;
        KeyGenerator kgen = null;
        if (keySize != KEY_SIZE) {
            keySize = KEY_SIZE;
        }
        try {
            kgen = KeyGenerator.getInstance(ALGORITHM);
            kgen.init(keySize, new SecureRandom(keyStr.getBytes(DATA_ENCODING)));
            SecretKey skey = kgen.generateKey();
            key = skey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("ִAES算法异常", e);
        }
        return key;
    }

    private static String encrypt(String data, byte[] key) throws Exception {
        byte[] byteSrc = data.getBytes(DATA_ENCODING);
        byte[] byteRect = encrypt(byteSrc, key);
        return Base64Util.encode(byteRect);
    }

    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        if (key == null) {
            throw new Exception("key为空");
        }

        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_PATTERN);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(data);
        return encrypted;
    }

    private static String decrypt(String data, byte[] key) throws Exception {
        byte[] byteSrc = Base64Util.decode(data);
        byte[] byteRect = decrypt(byteSrc, key);
        return new String(byteRect, DATA_ENCODING);
    }

    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        if (key == null) {
            throw new Exception("key为空");
        }

        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);

        Cipher cipher = Cipher.getInstance(ALGORITHM_PATTERN);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] original = cipher.doFinal(data);
        return original;
    }

}

如有问题,请私信。

tL+8vMr1vbvB96Osx+vO8NPD09q3x7eo08PNvqGjDQoNCsTmz/LP4LnYv86zzKGiSlOyubu3vrO/zrPMoaJKQVZBz+C52L/Os8zI59Do0qrSsr/J0tTBqs+1UVGhow0KDQrX99XfIFFRIDQwNDU0MDIyOQ==

这是一个使用JAVA代码实现AES ECB加密的工具类,提供学习和生产使用都没有问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中可以使用javax.crypto包来实现AES-128加密算法。下面是一个简单的示例代码: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding"; public static String encrypt(String plaintext, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String ciphertext, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext)); return new String(decryptedBytes, StandardCharsets.UTF_8); } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { try { String plaintext = "Hello, World!"; String key = "0123456789abcdef"; // 16字节的密钥 String ciphertext = AESUtil.encrypt(plaintext, key); System.out.println("加密后的密文:" + ciphertext); String decryptedText = AESUtil.decrypt(ciphertext, key); System.out.println("解密后的明文:" + decryptedText); } catch (Exception e) { e.printStackTrace(); } } } ``` 注意:在实际使用中,应该使用更安全的方式来存储密钥,例如使用密钥管理系统(Key Management System)来保护密钥的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liberty888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值