本文实例讲述了java实现的对称加密算法3des定义与用法。分享给大家供大家参考,具体如下:
一 为什么出现3des
1、返回柯克霍夫原则
2、存在安全问题
二 3des(triple des或desede)好处
1、密钥长度增强
2、迭代次数提高
三 3des相关参数
四 3des代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
package com.imooc.security.des;
import java.security.key;
import java.security.securerandom;
import javax.crypto.cipher;
import javax.crypto.keygenerator;
import javax.crypto.secretkey;
import javax.crypto.secretkeyfactory;
import javax.crypto.spec.desedekeyspec;
import org.apache.commons.codec.binary.base64;
public class imooc3des {
private static string src = "cakin24 security 3des" ;
public static void main(string[] args) {
jdk3des();
}
public static void jdk3des() {
try {
//生成key
keygenerator keygenerator = keygenerator.getinstance( "desede" );
//keygenerator.init(168);
keygenerator.init( new securerandom()); //默认长度
secretkey secretkey = keygenerator.generatekey();
byte [] byteskey = secretkey.getencoded();
//key转换
desedekeyspec desedekeyspec = new desedekeyspec(byteskey);
secretkeyfactory factory = secretkeyfactory.getinstance( "desede" );
key convertsecretkey = factory.generatesecret(desedekeyspec);
//加密
cipher cipher = cipher.getinstance( "desede/ecb/pkcs5padding" );
cipher.init(cipher.encrypt_mode, convertsecretkey);
byte [] result = cipher.dofinal(src.getbytes());
system.out.println( "jdk 3des encrypt : " + base64.encodebase64string(result));
//解密
cipher.init(cipher.decrypt_mode, convertsecretkey);
result = cipher.dofinal(result);
system.out.println( "jdk 3des decrypt : " + new string(result));
} catch (exception e) {
e.printstacktrace();
}
}
}
|
五 实现效果
jdk 3des encrypt : 6t7a/rnardzsl+mtezvbfxwnnzr0yjbw
jdk 3des decrypt : cakin24 security 3des
注:这里引入了org.apache.commons.codec.binary.base64
包,可点击此处本站下载。
希望本文所述对大家java程序设计有所帮助。
原文链接:https://blog.csdn.net/chengqiuming/article/details/78746057