博客
关于我
加解密:基于 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 加密算法详解

你可能感兴趣的文章
mysql时间表示和计算
查看>>
MySQL是如何做容器测试的?
查看>>
mysql更改数据库表utf-8_修改mysql数据库为 utf-8
查看>>
mysql更改表引擎INNODB为MyISAM的方法总结
查看>>
mysql更新一个表里的字段等于另一个表某字段的值
查看>>
Mysql更新时间列只改日期为指定日期不更改时间
查看>>
MySQL更新锁(for update)摘要
查看>>
mysql更新频率_MySQL优化之如何了解SQL的执行频率
查看>>
mysql替换表的字段里面内容
查看>>
MySQL最多能有多少连接
查看>>
MySQL最大建议行数 2000w,靠谱吗?
查看>>
MySQL有哪些锁
查看>>
MySQL服务器安装(Linux)
查看>>
mysql服务器查询慢原因分析方法
查看>>
mysql服务无法启动的问题
查看>>
MySQL杂谈
查看>>
mysql权限
查看>>
mysql条件查询
查看>>
MySQL条件查询
查看>>
MySQL架构与SQL的执行流程_1
查看>>