关键字: des, 对称加密算法
import java.security.Key; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * DES安全编码组件 * * @author 梁栋 * @version 1.0 * @since 1.0 */ public abstract class DESCoder extends Coder { public static final String ALGORITHM = "DES"; /** * 取得密钥 * * @param key * @return * @throws Exception */ public static byte[] getKey(byte[] key) throws Exception { return encryptSHA(encryptMD5(key)); } /** * 加密 * * @param data * @param key * @return * @throws Exception */ public static byte[] encode(byte[] data, byte[] key) throws Exception { DESKeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey secretKey = keyFactory.generateSecret(dks); return encode(data, secretKey); } /** * 加密 * * @param data * @param key * @return * @throws Exception */ public static byte[] encode(byte[] data, Key key) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(data); } /** * 解密 * * @param str * @param key * @return * @throws Exception */ public static byte[] decode(byte[] data, byte[] key) throws Exception { DESKeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey secretKey = keyFactory.generateSecret(dks); return decode(data, secretKey); } /** * 解密 * * @param data * @param key * @return * @throws Exception */ public static byte[] decode(byte[] data, Key key) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(data); } }
import static org.junit.Assert.*; import org.junit.Test; /** * * @author 梁栋 * @version 1.0 * @since 1.0 */ public class DESCoderTest { @Test public void test() { try { String inputStr = "DES"; String key = "中文"; byte[] keyBytes = DESCoder.getKey(key.getBytes()); System.err.println("原文:\t" + inputStr); System.err.println("密钥:\t" + new String(keyBytes)); byte[] inputData = inputStr.getBytes(); inputData = DESCoder.encode(inputData, keyBytes); System.err.println("加密后:\t" + new String(inputData)); byte[] outputData = DESCoder.decode(inputData, keyBytes); String outputStr = new String(outputData); System.err.println("解密后:\t" + outputStr); assertEquals(inputStr, outputStr); } catch (Exception e) { e.printStackTrace(); } } }
原文: DES 密钥: .+ g M[ = g 加密后: Yg)w 解密后: DES
/** * DES key size must be equal to 56 * DESede(TripleDES) key size must be equal to 112 or 168 * AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available * Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive) * RC2 key size must be between 40 and 1024 bits * RC4(ARCFOUR) key size must be between 40 and 1024 bits **/