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

    程序:

    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 DESede_Test {
        public static void main(String... args) {
            String original="Let’s Build a Giant Airship 青海长云暗雪山";
            System.out.println("原文=	"+original);
            
            try {
                // 生产密钥
                KeyGenerator kgen = KeyGenerator.getInstance("DESede");
                kgen.init(168);    //112 或168        
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "DESede");// 密钥,下面加密解密都要用到
                System.out.println("密钥=	"+Base64.encodeBase64String(key.getEncoded()));
                
                // 加密
                Cipher cipherEncode = Cipher.getInstance("DESede");
                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("DESede");// 创建密码器
                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 青海长云暗雪山
    密钥=    JvETf/fvSj34Q6QCvPTgq9mnGci17Aur
    密文=    7AnmFkcOIZrGj0uedu1j+J2ElY0J52JWL93EuNYfx8QFR2xLfAv6QXewazk8wG5G
    解密后=    Let’s Build a Giant Airship 青海长云暗雪山

    END

  • 相关阅读:
    4.5计算机网络笔记
    3.29计算机网络笔记
    3.22计算机网络笔记
    3.15计算机网络笔记
    用int类型表示最大公倍数
    markdown入门
    learning by doing
    技术博客(初用markdown)。
    物联网PPT智能家居王思齐和陈由钧第10组
    第六次java作业
  • 原文地址:https://www.cnblogs.com/heyang78/p/15364018.html
Copyright © 2011-2022 走看看