对称加密采用ASC加密算法
package com.encrypt.impl;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import com.encrypt.IEncrypt;
import com.utils.HexUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class ASCEncrypt implements IEncrypt {
private String key;
public ASCEncrypt(String key) {
this.key = key;
}
@Override
public String encrypt(String string) {
String base64Encode = null;
try {
base64Encode = base64Encode(aesEncryptToBytes(string, key));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return HexUtil.bytes2Hex(base64Encode.getBytes());
}
@Override
public String decrypt(String string) {
byte[] bytes = HexUtil.hex2Bytes(string);
String aesDecrypt = null;
try {
String string2 = new String(bytes,"utf-8"); //转回来要注意编码的问题
aesDecrypt = aesDecrypt(string2, key);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return aesDecrypt;
}
/**
* 将base 64 code AES解密
*
* @param encryptStr
* 待解密的base 64 code
* @param decryptKey
* 解密密钥
* @return 解密后的string
* @throws Exception
*/
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return encryptStr.isEmpty() ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
/**
* AES解密
*
* @param encryptBytes
* 待解密的byte[]
* @param decryptKey
* 解密密钥
* @return 解密后的String
* @throws Exception
*/
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(decryptKey.getBytes()));
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
/**
* base 64 decode
*
* @param base64Code
* 待解码的base 64 code
* @return 解码后的byte[]
* @throws Exception
*/
public static byte[] base64Decode(String base64Code) throws Exception {
return base64Code.isEmpty() ? null : new BASE64Decoder().decodeBuffer(base64Code);
}
/**
* base 64 encode
*
* @param bytes
* 待编码的byte[]
* @return 编码后的base 64 code
*/
public static String base64Encode(byte[] bytes) {
return new BASE64Encoder().encode(bytes);
}
/**
* AES加密
*
* @param content
* 待加密的内容
* @param encryptKey
* 加密密钥
* @return 加密后的byte[]
* @throws Exception
*/
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(encryptKey.getBytes()));
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
}
非对称加密采用RSA加密算法
package com.encrypt.impl;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.encrypt.IEncrypt;
import com.utils.HexUtil;
import sun.misc.BASE64Encoder;
public class RSAEncrypt implements IEncrypt {
private PublicKey publicKey;
private PrivateKey privateKey;
private String publicKeyString;
private String privateKeyString;
// 加解密类
private Cipher cipher;
public RSAEncrypt(PublicKey publicKey, PrivateKey privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* 加密
*/
@Override
public String encrypt(String string) {
String afterEncrypt = null;
try {
// 加解密类
cipher = Cipher.getInstance("RSA");// Cipher.getInstance("RSA/ECB/PKCS1Padding");
// 明文
byte[] plainText = string.getBytes();
// 公钥加密
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enBytes = cipher.doFinal(plainText);
afterEncrypt = HexUtil.bytes2Hex(enBytes);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return afterEncrypt;
}
/**
* 解密
*/
@Override
public String decrypt(String string) {
byte[] bytes = HexUtil.hex2Bytes(string);
String afterDecrypt = null;
// 加解密类
try {
cipher = Cipher.getInstance("RSA");// Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] deBytes = cipher.doFinal(bytes);
publicKeyString = getKeyString(publicKey);
privateKeyString = getKeyString(privateKey);
afterDecrypt = new String(deBytes);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return afterDecrypt;
}
/**
* 得到密钥字符串(经过base64编码)
*
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
return (new BASE64Encoder()).encode(keyBytes);
}
}
不可逆加密采用MD5加密算法
package com.encrypt.impl;
import java.security.MessageDigest;
import com.encrypt.IEncrypt;
import com.utils.HexUtil;
public class MD5Encrypt implements IEncrypt {
@Override
public String encrypt(String string) {
String md5str = "";
string += "hengtian"; // 加盐
try {
// 1 创建一个提供信息摘要算法的对象,初始化为md5算法对象
MessageDigest md = MessageDigest.getInstance("MD5");
// 2 将消息变成byte数组
byte[] input = string.getBytes();
// 3 计算后获得字节数组,这就是那128位了
byte[] buff = md.digest(input);
// 4 把数组每一字节(一个字节占八位)换成16进制连成md5字符串
md5str = HexUtil.bytes2Hex(buff);
} catch (Exception e) {
e.printStackTrace();
}
return md5str;
}
/**
* MD5不可解密
*/
@Override
public String decrypt(String string) {
return null;
}
}
以上用到的工具类
package com.encrypt.impl;
public class HexUtil {
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* 将byte数组转为16进制
* @param src
* @return
*/
public static String bytes2Hex(byte[] src){
char[] res = new char[src.length*2];
final char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
for(int i=0,j=0; i<src.length; i++){
res[j++] = hexDigits[src[i] >>>4 & 0x0f];
res[j++] = hexDigits[src[i] & 0x0f];
}
return new String(res);
}
/**
* 将16进制转为byte数组
* @param src
* @return
*/
public static byte[] hex2Bytes(String src){
byte[] res = new byte[src.length()/2];
char[] chs = src.toCharArray();
int[] b = new int[2];
for(int i=0,c=0; i<chs.length; i+=2,c++){
for(int j=0; j<2; j++){
if(chs[i+j]>='0' && chs[i+j]<='9'){
b[j] = (chs[i+j]-'0');
}else if(chs[i+j]>='A' && chs[i+j]<='F'){
b[j] = (chs[i+j]-'A'+10);
}else if(chs[i+j]>='a' && chs[i+j]<='f'){
b[j] = (chs[i+j]-'a'+10);
}
}
b[0] = (b[0]&0x0f)<<4;
b[1] = (b[1]&0x0f);
res[c] = (byte) (b[0] | b[1]);
}
return res;
}
public static byte[] decodeHex(final char[] data) throws Exception {
final int len = data.length;
if ((len & 0x01) != 0) {
throw new Exception("Odd number of characters.");
}
final byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f = f | toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
protected static int toDigit(final char ch, final int index)
throws Exception {
final int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new Exception("Illegal hexadecimal character " + ch
+ " at index " + index);
}
return digit;
}
public static char[] encodeHex(final byte[] data) {
return encodeHex(data, true);
}
public static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
protected static char[] encodeHex(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
}
测试
package com.encrypt.impl;
import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class Test {
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
String pwd = "thisispwd";
System.out.println("MD5加密后\t" + new MD5Encrypt().encrypt(pwd));
String ascKey = "this is ascKey";
String afterASCEncrypt = new ASCEncrypt(ascKey).encrypt(pwd);
System.out.println("asc加密后:\t" + afterASCEncrypt);
System.out.println("asc解密后:\t" + new ASCEncrypt(ascKey).decrypt(afterASCEncrypt));
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 密钥位数
keyPairGen.initialize(1024);
// 密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAEncrypt rsaEncrypt = new RSAEncrypt(publicKey, privateKey);
String afterRSAEncrypt = rsaEncrypt.encrypt(pwd);
System.out.println("rsa加密后\t" + afterRSAEncrypt);
System.out.println("rsa解密后:\t" + rsaEncrypt.decrypt(afterRSAEncrypt));
}
}
运行结果:
MD5加密后 D3F80FD1DB1C81230185E410CA34ABE9
asc加密后: 7836747664347666457A66706A5338566B4157354E773D3D
asc解密后: thisispwd
rsa加密后 048ACE6B384EC2015944E2F18F20BF882803D22F402DC6543A6BBA8B120576C0DAAB0647DAC7CDBAC7075B73207AB1BAF6B6EF363093E392C12280A86257F81183648CADC98E019CDB595F9DB551B9D0543622AD3E2B20B8C8C6181CE4A766DFAAA14033BC251EEE59F6EF421DD5E74EBDAAE90CB077A08636104CABABDFB973
rsa解密后: thisispwd