分类: Java
2010-04-27 15:40:23
Triple DES uses a "key bundle" which comprises three DES , K1, K2 and K3, each of 56 bits (excluding ). The encryption algorithm is:
ciphertext = EK3(DK2(EK1(plaintext)))
I.e., DES encrypt with K1, DES decrypt with K2, then DES encrypt with K3.
Decryption is the reverse:
plaintext = DK1(EK2(DK3(ciphertext)))
I.e., decrypt with K3, encrypt with K2, then decrypt with K1.
Each triple encryption encrypts of 64 bits of data.
The standards define three keying options:
eg:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class Des {
private static final String Algorithm = "DESede";
public static final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58, (byte)0x88, 0x10, 0x40, 0x38
, 0x28, 0x25, 0x79, 0x51, (byte)0xCB, (byte)0xDD, 0x55, 0x66
, 0x77, 0x29, 0x74, (byte)0x98, 0x30, 0x40, 0x36, (byte)0xE2};
//24字节的密钥
/*
* @ use DESede algorithm to encrpty the src
* @ keybyte: secretkey 24 byte
* @ src:the text needs to be encrypt
* @ return the enc result
*/
public static byte[] encryptMode (byte[] keybyte, byte[] src) {
try {
SecretKey deskey = new SecretKeySpec (keybyte, Algorithm);
Cipher c1 = Cipher.getInstance ("DESede/ECB/PKCS5Padding");
c1.init (Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal (src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace ();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace ();
} catch (java.lang.Exception e3) {
e3.printStackTrace ();
}
return null;
}
/*
* @ use DESede algorithm to decrypt the src
* @ keybyte: secretkey 24 byte
* @ src:the text needs to be dec
* @ return the dec result
*/
public static byte[] decryptMode (byte[] keybyte, byte[] src) {
try {
SecretKey deskey = new SecretKeySpec (keybyte, Algorithm);
Cipher c1 = Cipher.getInstance ("DESede/ECB/PKCS5Padding");
c1.init (Cipher.DECRYPT_MODE, deskey);
return c1.doFinal (src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace ();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace ();
} catch (java.lang.Exception e3) {
e3.printStackTrace ();
}
return null;
}
}