对称加解密算法

1.AES加密和解密算法

以下是基于Java的代码实现

(1)说明

•generateKey 方法:生成一个 AES 密钥。

•encrypt 方法:接受明文字符串和密钥,返回加密后的 Base64 编码的字符串。

•decrypt 方法:接受加密后的 Base64 编码的字符串和密钥,返回解密后的明文字符串。

•main 方法:演示如何使用这些方法进行加密和解密。

(2)注意事项

•安全性:生成密钥时使用了 SecureRandom 来增加随机性,从而提高安全性。

•编码:加密和解密时使用了 UTF-8 编码,确保文本正确处理。

•异常处理:上述示例代码中包含了异常处理,但在实际应用中可能需要更细致的异常处理逻辑。

(3)扩展功能

如果你需要更多的功能,比如使用特定的密钥而不是每次都生成新的密钥,或者使用不同的填充模式(如 PKCS5Padding),你可以在 generateKey 方法中传递密钥字符串,或者在 Cipher.getInstance 方法中指定不同的转换模式。

package com.jz.modules.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @ClassName AESUtil
 * @Author 徐亚辉
 * @Date 16:05 2024/9/12
 * @Version 1.0
 * @Description AES 加密、解密工具类
 */
public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    /**
     * 加密方法
     * @param plainText
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密方法
     * @param encryptedText
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes, "UTF-8");
    }

    /**
     * 生成密钥方法
     * @return
     * @throws Exception
     */
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(new byte[16]);
        keyGen.init(128, secureRandom); // AES 默认使用 128 位密钥
        return keyGen.generateKey();
    }

    public static void main(String[] args) {
        try {
            SecretKey secretKey = generateKey();

            String plainText = "Hello, World!";
            String encryptedText = encrypt(plainText, secretKey);
            System.out.println("Encrypted Text: " + encryptedText);

            String decryptedText = decrypt(encryptedText, secretKey);
            System.out.println("Decrypted Text: " + decryptedText);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.Base64编码和解码

参考地址:https://www.cnblogs.com/softidea/p/6934972.html

Java实现base64编码的三种方式

Java中对进行Base64编码的有如下三种方式:

方式一:commons-codec.jar 【推荐】
官网:http://commons.apache.org/proper/commons-codec/archives/1.11/userguide.html
maven项目需要的依赖:

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>
String base64String="whuang123";
byte[] result = Base64.encodeBase64(base64String.getBytes());

方式二:使用sun.misc.BASE64Encoder

 /**
     * 编码
     *
     * @param content
     * @return
     */
    public static String encode(byte[] content) {
        return new sun.misc.BASE64Encoder().encode(content);
    }

    /**
     * 解码
     *
     * @param source
     * @return
     */
    public static byte[] decode(String source) {
        try {
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            return decoder.decodeBuffer(source);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

方式三:使用com.sun.org.apache.xerces.internal.impl.dv.util.Base64

/**
     * 编码
     *
     * @param input
     * @return
     * @throws Exception
     */
    public static String encodeBase64(byte[] input) throws Exception {
        Class clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod = clazz.getMethod("encode", byte[].class);
        mainMethod.setAccessible(true);
        Object retObj = mainMethod.invoke(null, new Object[]{input});
        return (String) retObj;
    }

    /**
     * 解码
     *
     * @param input
     * @return
     * @throws Exception
     */
    public static byte[] decodeBase64(String input) throws Exception {
        Class clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod = clazz.getMethod("decode", String.class);
        mainMethod.setAccessible(true);
        Object retObj = mainMethod.invoke(null, input);
        return (byte[]) retObj;
    } 

3.解码的时候出现中文乱码问题

如果发现项目部署之后,出现中文解码乱码的问题,则指定服务启动的编解码格式,可以解决,如下:

java -Dfile.encoding=UTF-8 -jar your-application.jar

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值