import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
/**
* Created with IntelliJ IDEA.
* User: HLW-RYH-1370
* Date: 2019/3/6
* Time: 9:24
* To change this template use File | Settings | File Templates.
*/
public class Base64Util {
/**
* des 加密
* @param plainText
* @param desKeyParameter 加密秘钥
* @return 二进制字节数组
* @throws Exception
*/
public static byte[] desEncrypt(byte[] plainText, String desKeyParameter) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKeyParameter.getBytes();
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
byte data[] = plainText;
byte encryptedData[] = cipher.doFinal(data);
return encryptedData;
}
/**
* des 解密
* @param encryptText
* @param desKeyParameter 解密秘钥
* @return 二进制字节数组
* @throws Exception
*/
public static byte[] desDecrypt(byte[] encryptText, String desKeyParameter) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKeyParameter.getBytes();
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key, sr);
byte encryptedData[] = encryptText;
byte decryptedData[] = cipher.doFinal(encryptedData);
return decryptedData;
}
/**
* 编码
*
* @param content
* @return
*/
public static String base64Encode(byte[] content) {
return new sun.misc.BASE64Encoder().encode(content);
}
/**
* 解码
*
* @param source
* @return
*/
public static byte[] base64Decode(String source) {
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
return decoder.decodeBuffer(source);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String base64DesDecode(String source,String key) {
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
return new String(desDecrypt(decoder.decodeBuffer(source),key));
} catch (IOException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public static String base64DesEncode(String source,String key) {
try {
return base64Encode(desEncrypt(source.getBytes(),key));
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String test = "Xe2/QEFxDkM=";
String key = "jiuzhouyl";
String a = base64DesDecode(test,key);
String b = base64DesEncode("0",key);
System.out.println(a+" "+b);
}
}
使用方式:
1、编码
将"0"编码成加密的base64,并附加秘钥
String b = base64DesEncode("0",key);
2、解码
将base64解码成"0",须提供秘钥
String a = base64DesDecode("Xe2/QEFxDkM=",key);