zoukankan      html  css  js  c++  java
  • 【Java/DES】使用DES加解密

    例程下载:

     https://files.cnblogs.com/files/heyang78/ufo_base64_des_211003am.rar

    需要导入的依赖:

            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>1.15</version>
            </dependency>

    程序:

    package ufo;
    
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    
    import org.apache.commons.codec.binary.Base64;
    
    public class DES_Test {
        public static void main(String... args) {
            String original="Let’s Build a Giant Airship 青海长云暗雪山";
            System.out.println("原文=	"+original);
            
            try {
                // 生产密钥
                KeyGenerator kgen = KeyGenerator.getInstance("DES");
                kgen.init(56);            
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "DES");// 密钥,下面加密解密都要用到
                System.out.println("密钥=	"+Base64.encodeBase64String(key.getEncoded()));
                
                // 加密
                Cipher cipherEncode = Cipher.getInstance("DES");
                byte[] byteContent = original.getBytes();
                cipherEncode.init(Cipher.ENCRYPT_MODE, key);
                byte[] EncodeResults = cipherEncode.doFinal(byteContent);
                System.out.println("密文=	"+Base64.encodeBase64String(EncodeResults));
                
                // 解密
                Cipher cipherDecode = Cipher.getInstance("DES");// 创建密码器
                cipherDecode.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
                byte[] DecodeResults = cipherDecode.doFinal(EncodeResults);
                System.out.println("解密后=	"+new String(DecodeResults));
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    输出:

    原文=    Let’s Build a Giant Airship 青海长云暗雪山
    密钥=    2nAyzeNe6UA=
    密文=    8OQw+fvxDTtlzLabEbfiJPgvJaPLTtDdWd0ALr1CDGetMpvTgEE+K2smBrhVfGBm
    解密后=    Let’s Build a Giant Airship 青海长云暗雪山
  • 相关阅读:
    运维岗春招--part2
    python 题库|刷题
    leetcode刷题
    运维面经汇总
    python自动化运维阅读笔记
    Python编程汇总
    old_boy 运维学习-第一期
    团队博客作业-Week3
    个人对final发布产品的排名
    各组对final发布产品的排名
  • 原文地址:https://www.cnblogs.com/heyang78/p/15364005.html
Copyright © 2011-2022 走看看