zoukankan      html  css  js  c++  java
  • 对称加密: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)); } }
  • 相关阅读:
    关于数据库 长度和小数点的关系和坑
    温故而知新,jquery选择器$=
    局域网访问本地localhost页面
    解决谷歌浏览器和360浏览器 input 自动填充淡黄色背景色的问题
    抢月饼 浏览器插件开发
    css 多行溢出
    ss服务待研究
    NUnit笔记
    5分钟实现VS2010整合NUnit进行单元测试
    vs2010中使用Nunit测试c#代码结果的正确性
  • 原文地址:https://www.cnblogs.com/nginxTest/p/15481015.html
Copyright © 2011-2022 走看看