接下來我們介紹對稱加密算法
DES
DES
DES算法把
通過java代碼實現如下
import java
import java
import javax
import javax
import javax
import javax
import javax
/** *//**
* DES安全編碼組件 author by ;
*
* <pre>
* 支持 DES
* DES key size must be equal to
* DESede(TripleDES) key size must be equal to
* AES key size must be equal to
* Blowfish key size must be multiple of
* RC
* RC
* 具體內容 需要關注 JDK Document&///docs/technotes/guides/security/l
* </pre>
*
* @author 梁棟
* @version
* @since
*/
public abstract class DESCoder extends Coder {
/** *//**
* ALGORITHM 算法 <br>
* 可替換為以下任意一種算法
*
* <pre>
* DES key size must be equal to
* DESede(TripleDES) key size must be equal to
* AES key size must be equal to
* Blowfish key size must be multiple of
* RC
* RC
* </pre>
*
* 在Key toKey(byte[] key)方法中使用下述代碼
* <code>SecretKey secretKey = new SecretKeySpec(key
* <code>
* DESKeySpec dks = new DESKeySpec(key);
* SecretKeyFactory keyFactory = SecretKeyFactory
* SecretKey secretKey = keyFactory
* </code>
*/
public static final String ALGORITHM =
/** *//**
* 轉換密鑰<br>
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory
SecretKey secretKey = keyFactory
// 當使用其他對稱加密算法時
// SecretKey secretKey = new SecretKeySpec(key
return secretKey;
}
/** *//**
* 解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data
Key k = toKey(decryptBASE
Cipher cipher = Cipher
cipher
return cipher
}
/** *//**
* 加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data
Key k = toKey(decryptBASE
Cipher cipher = Cipher
cipher
return cipher
}
/** *//**
* 生成密鑰
*
* @return
* @throws Exception
*/
public static String initKey() throws Exception {
return initKey(null);
}
/** *//**
* 生成密鑰
*
* @param seed
* @return
* @throws Exception
*/
public static String initKey(String seed) throws Exception {
SecureRandom secureRandom = null;
if (seed != null) {
secureRandom = new SecureRandom(decryptBASE
} else {
secureRandom = new SecureRandom();
}
KeyGenerator kg = KeyGenerator
kg
SecretKey secretKey = kg
return encryptBASE
}
}
延續上一個類的實現
再給出一個測試類
import static org
import org
/** *//**
*
* @author by ;;
* @version
* @since
*/
public class DESCoderTest {
@Test
public void test() throws Exception {
String inputStr =
String key = DESCoder
System
System
byte[] inputData = inputStr
inputData = DESCoder
System
byte[] outputData = DESCoder
String outputStr = new String(outputData);
System
assertEquals(inputStr
}
}
得到的輸出內容如下
原文
密鑰
加密後
解密後
由控制台得到的輸出
其實DES有很多同胞兄弟
/**
* DES key size must be equal to
* DESede(TripleDES) key size must be equal to
* AES key size must be equal to
* Blowfish key size must be multiple of
* RC
* RC
**/
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27624.html