sample code about TripleDES

刚刚对triple-DES 研究了一下,整理出了下面的代码:
[code]
package com.nxj.cpp.usersecurity.common.util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

/**
* The class is encryption/decryption the password by "Triple-DES" Algorithm.
* @author justin.gong
*
*/
public class TripleDES {

/**
* the file store key.
*/
private static File keyFile = new File("./secretKey");

/**
* store the key Object.
*/
private static SecretKey key = null;

static {
try {
if (!keyFile.exists()) {
key = generateKey();
writeKey(key, keyFile);
} else {
key = readKey();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}

/**
* Generate a secret TripleDES encryption/decryption key.
*/
private static SecretKey generateKey() throws NoSuchAlgorithmException {
// Get a key generator for Triple DES (a.k.a DESede)
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
// Use it to generate a key
return keygen.generateKey();
}

/**
* Save the specified TripleDES SecretKey to the specified file.
* @param key
* @param file
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private static void writeKey(SecretKey key, File file) throws IOException,
NoSuchAlgorithmException, InvalidKeySpecException {
// Convert the secret key to an array of bytes like this
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
DESedeKeySpec keyspec = (DESedeKeySpec) keyfactory.getKeySpec(key,
DESedeKeySpec.class);
byte[] rawkey = keyspec.getKey();

// Write the raw key to the file
FileOutputStream out = new FileOutputStream(file);
out.write(rawkey);
out.close();
}

/**
* Read a TripleDES secret key from the specified file.
* @return key created according to the keyfile
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws InvalidKeySpecException
*/
private static SecretKey readKey() throws IOException,
NoSuchAlgorithmException, InvalidKeyException,
InvalidKeySpecException {
// Read the raw bytes from the keyfile
DataInputStream in = new DataInputStream(new FileInputStream(keyFile));
byte[] rawkey = new byte[(int) keyFile.length()];
in.readFully(rawkey);
in.close();

// Convert the raw bytes to a secret key like this
DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
SecretKey key = keyfactory.generateSecret(keyspec);
return key;
}

/**
* encrypt the password.
* @param password
* @return password after encrypt
*/
public static String encrypt(String password) {
String encodedPassword = null;
try {
if ((password != null) && (!"".equals(password.trim()))
&& (key != null)) {
Cipher cipher;
cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = password.getBytes();
byte[] ciphertext = cipher.doFinal(cleartext);
StringBuffer buf = new StringBuffer();
for (int i = 0; i < ciphertext.length; i++) {
buf.append(Byte.toString(ciphertext[i]) + "|");
}
encodedPassword = buf.toString();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encodedPassword;
}

/**
* decrypt the password.
* @param password
* @return password after decrypt
*/
public static String decrypt(String password) {
String decodedPassword = null;
if ((password != null) && (!"".equals(password.trim()))
&& (key != null)) {
ArrayList<String> list = new ArrayList<String>();
StringTokenizer toker = new StringTokenizer(password, "|");
while (toker.hasMoreElements()) {
list.add(toker.nextToken());
}
byte[] cleartext = new byte[list.size()];
int i = 0;
for (Iterator iter = list.iterator(); iter.hasNext();) {
String element = (String) iter.next();
cleartext[i] = Byte.parseByte(element);
i++;
}

Cipher cipher;
try {
cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] ciphertext = cipher.doFinal(cleartext);
decodedPassword = new String(ciphertext);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
return decodedPassword;
}
}


[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值