最近项目紧,博客少有更新了。好不容易空闲下来再继续总结些东西。
之前对RSA算法进行了总结。今天将对称算法的部分补上,包括DES,3DES,AES三种。
基本上可说的部分不多,代码也好懂,便直接上CODE了。
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by user on 2018/1/30.
*/
public class CryptoUtil {
public enum ALGO{
DES,TripleDES,AES
}
public enum PADDING {
PKCS5,NO
}
public enum MODE{
CBC,ECB
}
public static byte[] process(ALGO algo,
MODE mode,
PADDING padding,
byte[] key,
byte[] data,
boolean doEncrypt){
try {
SecretKeySpec keySpec=new SecretKeySpec(key, toAlgoStr(algo));
Cipher cipher= Cipher.getInstance(toAlgoStr(algo)+"/"+toModeStr(mode)+"/"+toPaddingStr(padding));
if(mode==MODE.CBC){
cipher.init(doEncrypt?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE, keySpec,getIv(algo));
}else {
cipher.init(doEncrypt?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE, keySpec);
}
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}
public static String toAlgoStr(ALGO algo){
switch (algo){
case AES:
return "AES";
case DES:
return "DES";
case TripleDES:
return "DESede";
}
return null;
}
public static String toPaddingStr(PADDING PADDING){
switch (PADDING){
case NO:
return "NoPadding";
case PKCS5:
return "PKCS5Padding";
}
return null;
}
public static String toModeStr(MODE mode){
switch (mode){
case CBC:
return "CBC";
case ECB:
return "ECB";
}
return null;
}
private static IvParameterSpec getIv(ALGO algo){
int keyLen=0;
switch (algo){
case AES:
keyLen=16;
break;
case DES:
case TripleDES:
keyLen=8;
break;
}
byte[] IV_PARAMETER=new byte[keyLen];
Arrays.fill(IV_PARAMETER,(byte)0x00);
return new IvParameterSpec(IV_PARAMETER);
}
}