• 【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 青海长云暗雪山
  • 相关阅读:
    平衡二叉树
    二叉搜索树的最近公共祖先
    U-Boot> help, 命令集
    sprintf_s函数用法
    用keil编写的 C51错误 *** WARNING L1: UNRESOLVED EXTERNAL SYMBOL SYMBOL: ?C_START
    GPS时间系统概述和世界时系统
    浅析gcc、arm-linux-gcc和arm-elf-gcc关系
    如何删除电脑中使用过的COM端口
    飞鸽传书 绑定指定网卡
    UE 高亮 一个或多个关键字的方法
  • 原文地址:https://www.cnblogs.com/heyang78/p/15364005.html
Copyright © 2020-2023  润新知