概述
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
public class EncryptUtil {
private static Cipher ecipher;
private static Cipher dcipher;
// 必须24个字符
private static final String key = “:@1$7!a:@1$7!a*:@1$7!a”;
private static final String alg = “DESede”;
static {
try {
SecretKey skey = new SecretKeySpec(key.getBytes(), alg);
ecipher = Cipher.getInstance(alg);
dcipher = Cipher.getInstance(alg);
ecipher.init(Cipher.ENCRYPT_MODE, skey);
dcipher.init(Cipher.DECRYPT_MODE, skey);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 加密字符串
*
/
public static String encrypt(String str) {
if (str == null)
return “”;
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes(“UTF8”);
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
BASE64Encoder b = new BASE64Encoder();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.encode(enc, bos);
enc = bos.toByteArray();
return new String(enc);
} catch (Exception e) {
e.printStackTrace();
return “”;
}
}
/*
* 解密字符串
*
*/
public static String decrypt(String str) {
if (str == null)
return “”;
try {
// Decode base64 to get bytes
BASE64Decoder d = new BASE64Decoder();
byte[] dec = d.decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, “UTF8”);
} catch (Exception e) {
return str;
}
}
public static void main(String[] args) {
String ss = EncryptUtil.encrypt("Xkw@2019");
System.out.println(ss);
String ee = EncryptUtil.decrypt(ss);
System.out.println(ee);
}
}
最后
以上就是精明电灯胆为你收集整理的基于base64的加密解密的全部内容,希望文章能够帮你解决基于base64的加密解密所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复