介绍:对称加密算法就是加密密钥和解密密钥是相同的,解密算法是加密算法的逆运算。
对称加密算法包括:AES DES PBE IDEA
1.DES
现在新的项目中很少使用,安全系数低,但是在对称加密算法中有很重要的历史地位。
代码实现:
package dms.java.base.security;
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class DESTest {
private static String src = "这是我的内容";
public static void main(String[] args) {
jdkDES();
bcDes();
}
/**
* jdk实现des加密
*/
public static void jdkDES(){
try {
// 生成key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
System.out.println("提供商:"+keyGenerator.getProvider());
SecretKey secretKey = keyGenerator.generateKey();
byte[] byteKey = secretKey.getEncoded();
// 转化key
DESKeySpec desKeySpec = new DESKeySpec(byteKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
Key converSecretKey = factory.generateSecret(desKeySpec);
// 加密
Cipher cipher = Cipher.getInstance("DES");
cipher.init(cipher.ENCRYPT_MODE, converSecretKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk DES encrypt :" + Hex.encodeHexString(result));
// 解密
cipher.init(cipher.DECRYPT_MODE, converSecretKey);
result = cipher.doFinal(result);
System.out.println("jdk DES decrypt :"+ new String(result));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* bouncy castle 实现des
* 最简单的方法就是增加实现提供商
*/
public static void bcDes(){
try {
Security.addProvider(new BouncyCastleProvider());
// 生成key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");// 参数要添加提供商,否则会仍然使用jdk
keyGenerator.init(56);
System.out.println("提供商:"+keyGenerator.getProvider());
SecretKey secretKey = keyGenerator.generateKey();
byte[] byteKey = secretKey.getEncoded();
// 转化key
DESKeySpec desKeySpec = new DESKeySpec(byteKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
Key converSecretKey = factory.generateSecret(desKeySpec);
// 加密
Cipher cipher = Cipher.getInstance("DES");
cipher.init(cipher.ENCRYPT_MODE, converSecretKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("bc DES encrypt :" + Hex.encodeHexString(result));
// 解密
cipher.init(cipher.DECRYPT_MODE, converSecretKey);
result = cipher.doFinal(result);
System.out.println("bc DES decrypt :"+ new String(result));
} catch (Exception e) {
e.printStackTrace();
}
}
}
DES的应用: