博客
关于我
加解密:基于 java 实现 des ede3 cbc pkcs#5 算法
阅读量:203 次
发布时间:2019-02-28

本文共 2228 字,大约阅读时间需要 7 分钟。

Java实现 DES EDE3 CBC PKCS#5 加密算法

代码实现

以下是基于 Java 语言实现 DES EDE3 CBC PKCS#5 加密算法的代码示例:

import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESedeKeySpec;import javax.crypto.spec.IvParameterSpec;public class Test1280 {    private static final byte[] KEY = {        (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,        (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,        (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,        (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,        (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,        (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef    };        private static final byte[] IV = {        (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,        (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef    };        public static void printBytes(byte[] b) {        for (int i = 0; i < b.length; i++) {            if (i > 0) {                System.out.print(" ");            }            System.out.print("%02x".format(b[i]));        }        System.out.println();    }        public static void main(String[] args) {        try {            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");            SecretKey secretKey = keyFactory.generateSecretKey(new DESedeKeySpec(KEY));            Cipher cipher = Cipher.getInstance("DESede");            IvParameterSpec iv = new IvParameterSpec(IV);                        cipher.init(secretKey, iv);                        // 加密或解密操作            // 以下为示例,具体使用时请根据需求设置明文和密文            byte[] plaintext = ...; // 明文            byte[] cipherText = new byte[plaintext.length];            cipher.doFinal(plaintext, 0, plaintext.length, cipherText, 0, cipherText.length, IvParameterSpec.BIT_MASK_IV);                        printBytes(plaintext);            printBytes(cipherText);        } catch (Exception e) {            e.printStackTrace();        }    }}

执行结果

运行上述代码会输出以下十六进制加密结果:

64 5a 6b d6 bf f8 36 b2 4f d1 74 f6 e7 f6 af db 74 65 73 74 31 32 38 30

OpenSSL 实现对比

如果使用 OpenSSL 实现相同的加密算法,可以使用以下命令进行对比:

openssl des-ede3-cbc -iv "$IV" -key "$KEY" -in plaintext.bin -out ciphered.bin

进一步了解该算法的实现,可以参考以下文章:

DES EDE3 CBC PKCS#5 加密算法详解

你可能感兴趣的文章
Netty NIO transport && OIO transport
查看>>
netty php,netty
查看>>
Netty WebSocket客户端
查看>>
netty 主要组件+黏包半包+rpc框架+源码透析
查看>>
Vue过渡 & 动画---vue工作笔记0014
查看>>
Netty 异步任务调度与异步线程池
查看>>
Netty 的 Handler 链调用机制
查看>>
Netty 编解码器详解
查看>>
Netty 解决TCP粘包/半包使用
查看>>
Netty 调用,效率这么低还用啥?
查看>>
Netty+Protostuff实现单机压测秒级接收35万个对象实践经验分享
查看>>
Netty+SpringBoot+FastDFS+Html5实现聊天App详解(一)
查看>>
netty--helloword程序
查看>>
Netty5.x 和3.x、4.x的区别及注意事项(官方翻译)
查看>>
netty——bytebuf的创建、内存分配与池化、组成、扩容规则、写入读取、内存回收、零拷贝
查看>>
netty——Channl的常用方法、ChannelFuture、CloseFuture
查看>>
netty——Future和Promise的使用 线程间的通信
查看>>
netty——Handler和pipeline
查看>>
Vue输出HTML
查看>>
netty——黏包半包的解决方案、滑动窗口的概念
查看>>