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)); } }
  • 相关阅读:
    http基础知识总结
    unittest单元测试流程
    python测试框架nose
    HTML,CSS,JS之间的关系
    无法远程连接mysql,连接后也没有权限创建数据库
    Android 导入导出CSV,xls文件 .
    Android Sqlite 导入CSV文件 .
    用java开发的网站或者程序
    111个知名Java项目集锦,包括url和描述
    Ruby简介,附带示例程序
  • 原文地址:https://www.cnblogs.com/nginxTest/p/15481015.html
Copyright © 2011-2022 走看看