本文实例为大家讲解了一个适用于JavaSE/JavaEE/Android的Java加密解密工具,供大家学习,具体内容如下
package longshu.utils.security;
import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class EncryptDecrypt {
// 无需创建对象
private EncryptDecrypt() {
}
public static byte[] SHA1Bit(byte[] source) {
try {
MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
sha1Digest.update(source);
byte targetDigest[] = sha1Digest.digest();
return targetDigest;
} catch (NoSuchAlgorithmException e) {
thro ne RuntimeException(e);
}
}
public static String SHA1(String source) {
return byte2HexStr(SHA1Bit(source.getBytes()));
}
public static byte[] MD5Bit(byte[] source) {
try {
// 获得MD5摘要算法的 MessageDigest对象
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
md5Digest.update(source);
// 获得密文
return md5Digest.digest();
} catch (NoSuchAlgorithmException e) {
thro ne RuntimeException(e);
}
}
public static String MD5(String source) {
return byte2HexStr(MD5Bit(source.getBytes()));
}
public static String encodebase64(String source) {
Class clazz = null;
Method encodeMethod = null;
try {// 优先使用第三方库
clazz = Class.forName(".apache.mons.codec.binary.base64");
encodeMethod = clazz.getMethod("encodebase64", byte[].class);
System.out.println("encodebase64-->" + clazz);
System.out.println("encodeMethod-->" + encodeMethod);
// 反射方法 静态方法执行无需对象
return ne String((byte[]) encodeMethod.invoke(null, source.getBytes()));
} catch (ClassNotFoundException e) {
String vm = System.getProperty("java.vm.name");
System.out.println(vm);
try {
if ("Dalvik".equals(vm)) {// Android
clazz = Class.forName("android.util.base64");
// byte[] base64.encode(byte[] input,int flags)
encodeMethod = clazz.getMethod("encode", byte[].class, int.class);
System.out.println("encodebase64-->" + clazz);
System.out.println("encodeMethod-->" + encodeMethod);
return ne String((byte[]) encodeMethod.invoke(null, source.getBytes(), 0));
} else {// JavaSE/JavaEE
clazz = Class.forName("sun.misc.base64Encoder");
encodeMethod = clazz.getMethod("encode", byte[].class);
System.out.println("encodebase64-->" + clazz);
System.out.println("encodeMethod-->" + encodeMethod);
return (String) encodeMethod.invoke(clazz.neInstance(), source.getBytes());
}
} catch (ClassNotFoundException e1) {
return null;
} catch (Exception e1) {
return null;
}
} catch (Exception e) {
return null;
}
// return base64.encodeToString(source, base64.DEFAULT);
// return ne String(base64.encode(source.getBytes(), base64.DEFAULT));
// sun.misc.base64Encoder
// base64Encoder encoder = ne base64Encoder();
// return encoder.encode(source.getBytes());
// .apache.mons.codec.binary.base64
// return ne String(base64.encodebase64(source.getBytes()));
}
public static String decodebase64(String encodeSource) {
Class clazz = null;
Method decodeMethod = null;
try {// 优先使用第三方库
clazz = Class.forName(".apache.mons.codec.binary.base64");
decodeMethod = clazz.getMethod("decodebase64", byte[].class);
System.out.println("decodebase64-->" + clazz);
System.out.println("decodeMethod-->" + decodeMethod);
// 反射方法 静态方法执行无需对象
return ne String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes()));
} catch (ClassNotFoundException e) {
String vm = System.getProperty("java.vm.name");
System.out.println(vm);
try {
if ("Dalvik".equals(vm)) {// Android
clazz = Class.forName("android.util.base64");
// byte[] base64.decode(byte[] input, int flags)
decodeMethod = clazz.getMethod("decode", byte[].class, int.class);
System.out.println("decodebase64-->" + clazz);
System.out.println("decodeMethod-->" + decodeMethod);
return ne String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes(), 0));
} else { // JavaSE/JavaEE
clazz = Class.forName("sun.misc.base64Decoder");
decodeMethod = clazz.getMethod("decodeBuffer", String.class);
System.out.println("decodebase64-->" + clazz);
System.out.println("decodeMethod-->" + decodeMethod);
return ne String((byte[]) decodeMethod.invoke(clazz.neInstance(), encodeSource));
}
} catch (ClassNotFoundException e1) {
return null;
} catch (Exception e1) {
return null;
}
} catch (Exception e) {
return null;
}
// return ne
// String(base64.decode(encodeSource.getBytes(),base64.DEFAULT));
// sun.misc.base64Decoder
// try {
// base64Decoder decoder = ne base64Decoder();
// return ne String(decoder.decodeBuffer(encodeSource));
// } catch (IOException e) {
// thro ne RuntimeException(e);
// }
// .apache.mons.codec.binary.base64
// return ne String(base64.decodebase64(encodeSource.getBytes()));
}
public static byte[] encryptBitAES(byte[] content, String passord) {
try {
Cipher encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
encryptCipher.init(Cipher.ENCRYPT_MODE, getKey(passord));// 初始化
byte[] result = encryptCipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static byte[] decryptBitAES(byte[] content, String passord) {
try {
Cipher decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
decryptCipher.init(Cipher.DECRYPT_MODE, getKey(passord));// 初始化
byte[] result = decryptCipher.doFinal(content);
return result; // 加密结果
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static String encryptAES(String content, String passord) {
return byte2HexStr(encryptBitAES(content.getBytes(), passord));
}
public static String decryptAES(String content, String passord) {
return ne String(decryptBitAES(hexStr2Bytes(content), passord));
}
private static Key getKey(String passord) thros NoSuchAlgorithmException {
SecureRandom secureRandom = ne SecureRandom(passord.getBytes());
// 生成KEY
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
// 转换KEY
SecretKeySpec key = ne SecretKeySpec(enCodeFormat, "AES");
return key;
}
public static String byte2HexStr(byte[] bytes) {
int bytesLen = bytes.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer hexString = ne StringBuffer(bytesLen 2);
for (int i = 0; i < bytesLen; i++) {
// 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() < 2) {
hexString.append(0);// 如果为1位 前面补个0
}
hexString.append(hex);
}
return hexString.toString();
}
public static byte[] hexStr2Bytes(String strIn) {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = ne byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = ne String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
}