Java對稱加密,非對稱加密,不可逆加密Util

NO IMAGE

對稱加密採用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