Java对称加密算法之AES

来源:互联网 发布:小成本知乎 编辑:程序博客网 时间:2024/05/16 14:50

【AES】

一种对称加密算法,DES的取代者。

加密相关文章见:Java加密技术


【代码】

import org.bouncycastle.crypto.BufferedBlockCipher;import org.bouncycastle.crypto.CipherParameters;import org.bouncycastle.crypto.DataLengthException;import org.bouncycastle.crypto.InvalidCipherTextException;import org.bouncycastle.crypto.engines.AESEngine;import org.bouncycastle.crypto.params.KeyParameter;import org.bouncycastle.util.encoders.Hex;/** * 功能:AES加密解密工具类 * @date : 2016-01-27 */public class AesUtil {/** * 对密码进行解密操作 * @param strPlain 密文 * @param key 解密密钥 * @return */public static String decrypt(String strPlain,String key){BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine());CipherParameters param = new KeyParameter(Hex.decode(key));cipher.init(false, param);byte[] output = Hex.decode(strPlain);byte[] out = new byte[output.length];        int len2 = cipher.processBytes(output, 0, output.length, out, 0);        try {cipher.doFinal(out, len2);return new String(out);} catch (DataLengthException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvalidCipherTextException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "";}/** * 对密码进行加密操作 * @param password * @param key * @return */public static String encrypt(String password,String key){BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine());CipherParameters    param = new KeyParameter(Hex.decode(key));//keybyte[]  input =password.getBytes();byte[]  out = new byte[input.length];cipher.init(true, param);int len1 = cipher.processBytes(input, 0, input.length, out, 0);        try {cipher.doFinal(out, len1);String str = new String(Hex.encode(out));return str;} catch (DataLengthException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvalidCipherTextException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "";}/** * 对密码进行加0操作 * @param password * @return */public static String addzero(String password){int length = password.length();if(length<30){for(int i=length;i<30;i++){password=password+"0";}}if(length>9){password = password + String.valueOf(length);}else{password = password + "0" + String.valueOf(length);}//System.out.println(password);return password;}/** * 对密码进行还原操作,去除之前添加的0 * @param password * @return */public static String removezero(String password){if(!Validators.isNull(password)&&password.length()==32){String length = password.substring(30, 32);char c = length.charAt(0);if(c == '0'){length = length.substring(1, 2);}return password.substring(0, Integer.parseInt(length));}return "";}}


String password = AesUtil.encrypt(AesUtil.addzero(pwd),HashHelper.MD5Encode(hashKey));//加密

String password = AesUtil.removezero(AesUtil.decrypt(pwd,HashHelper.MD5Encode(key)));// 解密


0 0
原创粉丝点击