对称加密:AES

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密、解密
 */

public class EncryptionAndDecryption {
    // 私钥
    private static String salt = "1111111111111111";

    /**
     * 加密
     *
     * @param encryptMessage 需要加密的信息
     * @return
     * @throws Exception
     */
    public static String encrypt(String encryptMessage) throws Exception {
        // 两个参数,第一个为私钥字节数组, 第二个为加密方式 AES或者DES
        SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
        // 实例化加密类,参数为加密方式,要写全
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化加密
        cipher.init(Cipher.ENCRYPT_MODE, key);
        // 加密操作,返回加密后的字节数组
        byte[] bytes = cipher.doFinal(encryptMessage.getBytes());
        String result = Base64.encodeBase64String(bytes);
        return result;
    }

    /**
     * 解密
     *
     * @param decryptMessage 需要解密的信息
     * @return
     * @throws Exception
     */
    public static String decrypt(String decryptMessage) throws Exception {
        // 先用Base64解
        byte[] bytes = Base64.decodeBase64(decryptMessage);
        SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化加密
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] ret = cipher.doFinal(bytes);
        String result = new String(ret, "utf-8");
        return result;
    }

  // 测试
public static void main(String[] args) throws Exception { String test = "123456"; String encrypt = encrypt(test); System.out.println("加密后信息encrypt:" + encrypt); System.out.println("解密后信息decrypt:" + decrypt(encrypt)); } }

 

posted @ 2021-10-29 16:16  蛋挞小子  阅读(72)  评论(0编辑  收藏  举报