<code
class
=
"lang-java"
>package com.ssh.util;
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.xerces.internal.impl.dv.util.Base64;
public
class
DESedeCoder {
public
static
final
String KEY_ALGORITHM =
"DESede"
;
public
static
final
String CIPHER_ALGORITHM =
"DESede/ECB/PKCS5Padding"
;
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;
}
public
static
Key toKey(byte[] key) throws Exception {
DESedeKeySpec dks =
new
DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(KEY_ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(dks);
return
secretKey;
}
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);
}
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);
}
public
static
String encode(String str,String screatKey){
String result =
""
;
byte[] data = DESedeCoder.encrypt(str.getBytes(), screatKey.getBytes());
result = Base64.encode(data);
return
result;
}
public
static
String decode(String str,String screatKey){
String result =
""
;
try
{
byte[] data = Base64.decode(str);
data = DESedeCoder.decrypt(data, screatKey.getBytes());
result =
new
String(data);
}
catch
(Exception e) {
e.printStackTrace();
}
return
result;
}
public
static
void main(String[] args) throws Exception {
String key =
"2C7dDYBy20mmKy3391xivikz"
;
String str =
"hello world~"
;
System.out.println(
"Key:"
+key);
System.out.println(
"原文:"
+ str);
String value = encode(str,key);
System.out.println(
"加密后:"
+ value);
System.out.println(
"解密后:"
+ decode(value,key));
}
}
</code>