---
title: "对称加密算法"
author: "icejadelove"
date: "2009-10-28T10:14:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-10-28T10:14:00Z"
id: 572008
url: "https://jdkdev.iteye.com/blog/572008"
---

原创作者: [snowolf](http://snowolf.iteye.com/blog/380034)

**DES**  
DES-Data Encryption Standard,即数据加密算法。是IBM公司于1975年研究成功并公开发表的。DES算法的入口参数有三个:Key、Data、Mode。其中Key为8个字节共64位,是DES算法的工作密钥;Data也为8个字节64位,是要被加密或被解密的数据;Mode为DES的工作方式,有两种:加密或解密。  
DES算法把64位的明文输入块变为64位的密文输出块,它所使用的密钥也是64位。  
![](http://www.iteye.com/upload/attachment/107373/1d78734d-67ad-3770-a790-88de5ac1857d.jpg)  
通过java代码实现如下：**Coder类见 [单向加密算法](http://www.iteye.com/wiki/security/1710-one-way-encryption-algorithm)**

Java代码

001. import java.security.Key;
002. import java.security.SecureRandom;
003. import javax.crypto.Cipher;
004. import javax.crypto.KeyGenerator;
005. import javax.crypto.SecretKey;
006. import javax.crypto.SecretKeyFactory;
007. import javax.crypto.spec.DESKeySpec;
008. /\**
009. \* DES安全编码组件
010. \*
011. \*
     
     ```
     
     ```
012. \* 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)
013. \* DES key size must be equal to 56
014. \* DESede(TripleDES) key size must be equal to 112 or 168
015. \* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
016. \* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
017. \* RC2 key size must be between 40 and 1024 bits
018. \* RC4(ARCFOUR) key size must be between 40 and 1024 bits
019. \* 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html
020. \*
021. \*
022. \* @author 梁栋
023. \* @version 1.0
024. \* @since 1.0
025. \*/
026. public abstract class DESCoder extends Coder {
027. /\**
028. \* ALGORITHM 算法
029. \* 可替换为以下任意一种算法，同时key值的size相应改变。
030. \*
031. \*
     
     ```
     
     ```
032. \* DES key size must be equal to 56
033. \* DESede(TripleDES) key size must be equal to 112 or 168
034. \* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
035. \* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
036. \* RC2 key size must be between 40 and 1024 bits
037. \* RC4(ARCFOUR) key size must be between 40 and 1024 bits
038. \*
039. \*
040. \* 在Key toKey(byte\[] key)方法中使用下述代码
041. \* `SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);` 替换
042. \*
043. \* DESKeySpec dks = new DESKeySpec(key);
044. \* SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
045. \* SecretKey secretKey = keyFactory.generateSecret(dks);
046. \*
047. \*/
048. public static final String ALGORITHM = "DES";
049. /\**
050. \* 转换密钥
051. \*
052. \* @param key
053. \* @return
054. \* @throws Exception
055. \*/
056. private static Key toKey(byte\[] key) throws Exception {
057. DESKeySpec dks = new DESKeySpec(key);
058. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
059. SecretKey secretKey = keyFactory.generateSecret(dks);
060. // 当使用其他对称加密算法时，如AES、Blowfish等算法时，用下述代码替换上述三行代码
061. // SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
062. return secretKey;
063. }
064. /\**
065. \* 解密
066. \*
067. \* @param data
068. \* @param key
069. \* @return
070. \* @throws Exception
071. \*/
072. public static byte\[] decrypt(byte\[] data, String key) throws Exception {
073. Key k = toKey(decryptBASE64(key));
074. Cipher cipher = Cipher.getInstance(ALGORITHM);
075. cipher.init(Cipher.DECRYPT\_MODE, k);
076. return cipher.doFinal(data);
077. }
078. /\**
079. \* 加密
080. \*
081. \* @param data
082. \* @param key
083. \* @return
084. \* @throws Exception
085. \*/
086. public static byte\[] encrypt(byte\[] data, String key) throws Exception {
087. Key k = toKey(decryptBASE64(key));
088. Cipher cipher = Cipher.getInstance(ALGORITHM);
089. cipher.init(Cipher.ENCRYPT\_MODE, k);
090. return cipher.doFinal(data);
091. }
092. /\**
093. \* 生成密钥
094. \*
095. \* @return
096. \* @throws Exception
097. \*/
098. public static String initKey() throws Exception {
099. return initKey(null);
100. }
101. /\**
102. \* 生成密钥
103. \*
104. \* @param seed
105. \* @return
106. \* @throws Exception
107. \*/
108. public static String initKey(String seed) throws Exception {
109. SecureRandom secureRandom = null;
110. if (seed != null) {
111. secureRandom = new SecureRandom(decryptBASE64(seed));
112. } else {
113. secureRandom = new SecureRandom();
114. }
115. KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
116. kg.init(secureRandom);
117. SecretKey secretKey = kg.generateKey();
118. return encryptBASE64(secretKey.getEncoded());
119. }
120. }

延续上一个类的实现，我们通过MD5以及SHA对字符串加密生成密钥，这是比较常见的密钥生成方式。  
再给出一个测试类：

Java代码

01. import static org.junit.Assert.\*;
02. import org.junit.Test;
03. /\**
04. \*
05. \* @author 梁栋
06. \* @version 1.0
07. \* @since 1.0
08. \*/
09. public class DESCoderTest {
10. @Test
11. public void test() throws Exception {
12. String inputStr = "DES";
13. String key = DESCoder.initKey();
14. System.err.println("原文:\\t" + inputStr);
15. System.err.println("密钥:\\t" + key);
16. byte\[] inputData = inputStr.getBytes();
17. inputData = DESCoder.encrypt(inputData, key);
18. System.err.println("加密后:\\t" + DESCoder.encryptBASE64(inputData));
19. byte\[] outputData = DESCoder.decrypt(inputData, key);
20. String outputStr = new String(outputData);
21. System.err.println("解密后:\\t" + outputStr);
22. assertEquals(inputStr, outputStr);
23. }
24. }

得到的输出内容如下：

Console代码

1. 原文: DES
2. 密钥: f3wEtRrV6q0=
3. 加密后: C6qe9oNIzRY=
4. 解密后: DES

由控制台得到的输出，我们能够比对加密、解密后结果一致。这是一种简单的加密解密方式，只有一个密钥。  
其实DES有很多同胞兄弟，如DESede(TripleDES)、AES、Blowfish、RC2、RC4(ARCFOUR)。这里就不过多阐述了，大同小异，只要换掉ALGORITHM换成对应的值，同时做一个代码替换**SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);**就可以了，此外就是密钥长度不同了。

Java代码

1. /\**
2. \* DES key size must be equal to 56
3. \* DESede(TripleDES) key size must be equal to 112 or 168
4. \* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
5. \* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
6. \* RC2 key size must be between 40 and 1024 bits
7. \* RC4(ARCFOUR) key size must be between 40 and 1024 bits
8. \*\*/