本工具采用的是DES SHA1PRNG 加密,如有興趣,讀者可由此自定義其他加密工具。具體可看代碼注釋
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* DESUtils 先采用BASE64Encoder對字符串進行處理,避免字符問題。
* 再采用des 標準的SHA1PRNG加密方法進行加密
*/
public class DESUtils {
private static Key key;
private static String KEY_STR = "webapp";//加密秘鑰,請自定義值
private static String charset = "UTF-8";
private static String type = "DES"; //加密標準
private static String method="SHA1PRNG"; //加密方法
private static Cipher cipher; //用于加解密操作的對象
//初始化key cipher
static {
try {
KeyGenerator generator = KeyGenerator.getInstance(type); //獲取秘鑰對象
SecureRandom secureRandom = SecureRandom.getInstance(method);//獲取加密算法的強隨機數對象
secureRandom.setSeed(KEY_STR.getBytes());//根據key_str生成強隨機數
generator.init(secureRandom);//初始化秘鑰對象
key = generator.generateKey();//生成key
generator = null;
cipher= Cipher.getInstance(type);//獲取cipher
cipher.init(Cipher.ENCRYPT_MODE, key);//根據key初始化cipher
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
}
//獲取加密后的字符串
public static String getEncryptString(String str) {
BASE64Encoder base64encoder = new BASE64Encoder();
byte[] bytes = new byte[0];
try {
bytes = str.getBytes(charset);
byte[] doFinal = new byte[0];
doFinal = cipher.doFinal(bytes);
return base64encoder.encode(doFinal);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e);
} catch (BadPaddingException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
//獲取加密后的字符串 將字符串解密
public static String getDecryptString(String str) {
BASE64Decoder base64decoder = new BASE64Decoder();
try {
byte[] bytes = base64decoder.decodeBuffer(str);
byte[] doFinal = cipher.doFinal(bytes);
return new String(doFinal, charset);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e);
} catch (BadPaddingException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
<center>Coding Blog ??? Github Blog </center>