package com.skycity.framework.utility;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.skycity.framework.Constant;
public class EncryptUtil {
// 加密字符串
public static String encryptMode(String keybyte, String src) {
try { // 生成密钥
SecretKey deskey = new SecretKeySpec(new BASE64Decoder().decodeBuffer(keybyte), Constant.ALGORITHM); // 加密
Cipher c1 = Cipher.getInstance(Constant.ALGORITHM);
c1.init(Cipher.ENCRYPT_MODE, deskey);
byte[] result = c1.doFinal(src.getBytes());
return new BASE64Encoder().encode(result);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
// 解密字符串
public static String decryptMode(String keybyte, String encryStr) {
try { // 生成密钥
SecretKey deskey = new SecretKeySpec(new BASE64Decoder().decodeBuffer(keybyte), Constant.ALGORITHM); // 解密
Cipher c1 = Cipher.getInstance(Constant.ALGORITHM);
c1.init(Cipher.DECRYPT_MODE, deskey);
byte[] result = c1.doFinal(new BASE64Decoder().decodeBuffer(encryStr));
return new String(result);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
//创建一个密钥
public static byte[] createSecretKey() {
KeyGenerator keygen = null;
try {
keygen = KeyGenerator.getInstance(Constant.ALGORITHM);
SecretKey deskey = keygen.generateKey();
return deskey.getEncoded();
} catch (Exception e) {
LogUtil.error("NoSuchAlgorithmException!");
}
return null;
}
public static void main(String[] args){
final byte[] keyBytes = createSecretKey();
String key= new BASE64Encoder().encode(keyBytes);
String szSrc = "admin";
System.out.println("加密前的字符串:" + szSrc);
String password = encryptMode(key,szSrc);
System.out.println("加密后的字符串:" + password);
String result = decryptMode(key, password);
System.out.println("解密后的字符串:" + result);
}
}
数据库表中有一个字段用于保存Key,一个字段用于保存password,更改密码的时候,重新生成一个KEY,然后生成一个PASSWORD,匹配保存到数据库中。
当登陆时,用数据库保存的KEY和password进行解密,然后与登陆时输入的password进行比较,如果相等,则成功。
算法支持
AES,DES,DESede,Blowfish等算法
|
|