Posted on 2013-05-25 01:50
zolly 阅读(8169)
评论(0) 编辑 收藏
DESede又称Triple-DES即三重DES加密算法,加强了DES的安全性,但速度稍慢,它是一种对称加密算法,加密解密都是用同一个密钥。本文介绍使用Java自带的API实现DEDede加密解密。
Bouncy Castle也支持DES算法,具体没有深入研究,有兴趣的可以下载相应的API进行测试。
http://www.bouncycastle.org/以下代码基本上覆盖了生成密钥以及加密解密的全过程,拷贝代码可以直接运行。(代码摘自网络)
每次生成密钥都会不一样,一般来说密钥需要生成文件并妥善保存。
DESedeCoder.java
package com.zolly.bouncycastle;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;
/**
* DESede对称加密算法演示
*
* @author zolly
* */
public class DESedeCoder {
/**
* 密钥算法
* */
public static final String KEY_ALGORITHM = "DESede";
/**
* 加密/解密算法/工作模式/填充方式
* */
public static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
/**
*
* 生成密钥
*
* @return byte[] 二进制密钥
* */
public static byte[] initkey() throws Exception {
// 实例化密钥生成器
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
// 初始化密钥生成器
kg.init(168);
// 生成密钥
SecretKey secretKey = kg.generateKey();
// 获取二进制密钥编码形式
byte[] key = secretKey.getEncoded();
BufferedOutputStream keystream =
new BufferedOutputStream(new FileOutputStream("DESedeKey.dat"));
keystream.write(key, 0, key.length);
keystream.flush();
keystream.close();
return key;
}
/**
* 转换密钥
*
* @param key
* 二进制密钥
* @return Key 密钥
* */
public static Key toKey(byte[] key) throws Exception {
// 实例化Des密钥
DESedeKeySpec dks = new DESedeKeySpec(key);
// 实例化密钥工厂
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(KEY_ALGORITHM);
// 生成密钥
SecretKey secretKey = keyFactory.generateSecret(dks);
return secretKey;
}
/**
* 加密数据
*
* @param data
* 待加密数据
* @param key
* 密钥
* @return byte[] 加密后的数据
* */
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 还原密钥
Key k = toKey(key);
// 实例化
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, k);
// 执行操作
return cipher.doFinal(data);
}
/**
* 解密数据
*
* @param data
* 待解密数据
* @param key
* 密钥
* @return byte[] 解密后的数据
* */
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 欢迎密钥
Key k = toKey(key);
// 实例化
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, k);
// 执行操作
return cipher.doFinal(data);
}
/**
* 进行加解密的测试
*
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String str = "DESede";
System.out.println("原文:" + str);
// 初始化密钥
byte[] key = DESedeCoder.initkey();
System.out.println("密钥:" + Base64.encode(key));
// 加密数据
byte[] data = DESedeCoder.encrypt(str.getBytes(), key);
System.out.println("加密后:" + Base64.encode(data));
// 解密数据
data = DESedeCoder.decrypt(data, key);
System.out.println("解密后:" + new String(data));
}
}
正对以上代码,我进行了适当修改,使其变得更加实用。我的主要应用是把客户的数据加密保存到数据库,取出来的时候再解密,保证数据库数据的安全。注意我固定了密钥,以防密钥一旦丢失,所有数据都变成乱码了,固定密钥安全性有所降低,但是对数据库字段加密安全性已经足够了。
DESedeTest.java
package com.zolly.bouncycastle;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class DESedeTest {
/**
* @param args
*/
public static void main(String[] args) {
String strText = "This is a testing";
String text1 = DESedeTest.encryptProperty(strText);
String text2 = DESedeTest.decryptProperty(text1);
System.out.println(text1);
System.out.println(text2);
}
public static String encryptProperty(String clearText) {
String KEY_STRING = "RRYa6li5NGFodgKUtvS1I6fZwY8xpJjI";
byte[] key = null;
try {
key = Base64.decode(KEY_STRING);
} catch (Base64DecodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return DESedeTest.performDESedeCoder(clearText, key, true);
}
public static String decryptProperty(String cipherText) {
String KEY_STRING = "RRYa6li5NGFodgKUtvS1I6fZwY8xpJjI";
byte[] key = null;
try {
key = Base64.decode(KEY_STRING);
} catch (Base64DecodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return DESedeTest.performDESedeCoder(cipherText, key, false);
}
public static String performDESedeCoder(String inputValue, byte[] key,
boolean encrypt) {
String rtnValue = "";
String KEY_ALGORITHM = "DESede";
String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
byte[] data = null;
try {
DESedeKeySpec dks = new DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(KEY_ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] input = null;
if (encrypt) {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
input = inputValue.getBytes();
} else {
cipher.init(Cipher.DECRYPT_MODE, secretKey);
input = Base64.decode(inputValue);
}
data = cipher.doFinal(input);
} catch (InvalidKeyException e) {
System.out.println(e.getMessage());
} catch (NoSuchAlgorithmException e) {
System.out.println(e.getMessage());
} catch (InvalidKeySpecException e) {
System.out.println(e.getMessage());
} catch (NoSuchPaddingException e) {
System.out.println(e.getMessage());
} catch (IllegalBlockSizeException e) {
System.out.println(e.getMessage());
} catch (BadPaddingException e) {
System.out.println(e.getMessage());
} catch (Base64DecodingException e) {
System.out.println(e.getMessage());
}
if (data == null) {
rtnValue = inputValue;
} else {
if (encrypt) {
rtnValue = com.sun.org.apache.xml.internal.security.utils.Base64
.encode(data);
} else {
rtnValue = new String(data);
}
}
return rtnValue;
}
}