import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import sun.misc.BASE64Decoder;
public class Crypt {
private static final byte[] key = "MyKey".getBytes();
private static String Algorithm = "DES"; // 定义 加密算法,可用
// DES,DESede,Blowfish
static boolean debug = false;
static {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
}
// 加密
public static String encode(String input) throws Exception {
if (input == null)
return null;
byte[] bytes = input.getBytes();
SecretKey deskey = new javax.crypto.spec.SecretKeySpec(key, Algorithm);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
byte[] cipherByte = c1.doFinal(bytes);
return byte2hex(cipherByte);
}
// 解密
public static String decode(String input) throws Exception {
if (input == null)
return null;
byte[] bytes = hex2byte(input);
SecretKey deskey = new javax.crypto.spec.SecretKeySpec(key, Algorithm);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
byte[] clearByte = c1.doFinal(bytes);
return new String(clearByte);
}
// 字节码转换成16进制字符串
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
// 将16进制字符串转换成字节码
public static byte[] hex2byte(String hex) {
byte[] bts = new byte[hex.length() / 2];
for (int i = 0; i < bts.length; i++) {
bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2),
16);
}
return bts;
}
public static void main(String[] args) throws Exception {
debug = false;
String testStr = "Hello fox";
long s = System.currentTimeMillis();
System.out.println(encode(testStr));
System.out.println(decode(encode(testStr)));
System.out.println(encode(testStr));
System.out.println(decode(encode(testStr)));
System.out.println(encode(testStr));
System.out.println(decode(encode(testStr)));
System.out.println(encode(testStr));
System.out.println(decode(encode(testStr)));
System.out.println(System.currentTimeMillis() - s);
}
public static String getFromBASE64(String s) {
if (s == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(s);
return new String(b);
}
catch (Exception e) {
return null;
}
}
}
利用JDK自带API进行加密和解密
最新推荐文章于 2023-10-19 15:08:19 发布