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)); } }
  • 相关阅读:
    Codeforces Round #627 (Div. 3) 总结
    [IOI1994] 时钟
    收集一些优秀的甲方安全开源项目
    python基础——对时间进行加减
    JSFinder:一个在js文件中提取URL和子域名的脚本
    python对齐输出
    python使用smtplib发送邮件
    任务2:扫描渗透测试(50分)[2019年信息安全管理与评估赛题答案-01]
    记一次Xmrig挖矿木马排查过程
    Bypass xss过滤的测试方法
  • 原文地址:https://www.cnblogs.com/nginxTest/p/15481015.html
Copyright © 2011-2022 走看看