AES加密解密
package com.ujia.util.security; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESUtil { /** *配置文件中保存的 AES的key,必须是16位 */ public final static String KEY = "^{Y1*-/?(i1Lo0|)"; /** * 配置文件中保存的AES的IV,必须是16位 */ public final static String IV = "{!y9+.*5Ty0S&%$]"; /** * 使用AES加密 * @param data 需要加密的明文 * @return 加密后的密文 */ public static String encrypt(String data) { try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); int blockSize = cipher. getBlockSize(); byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes. length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System. arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(), "AES" ); IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher. ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return new sun.misc.BASE64Encoder().encode(encrypted); } catch (Exception e) { e.printStackTrace(); return null; } } /** * AES解密 * @param data 需要解密的字符串 * @return 返回解密后的数据 * @throws Exception */ public static String desEncrypt(String data) throws Exception{ byte[] encrypted1 = new sun.misc.BASE64Decoder().decodeBuffer(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } }
MD5加密
package com.ujia.util.security; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; public class MD5Util { public static String MD5_String(String password) throws NoSuchAlgorithmException{ MessageDigest md5 = MessageDigest.getInstance("MD5"); BASE64Encoder base64 = new BASE64Encoder(); return base64.encode(md5.digest(password.getBytes())); } }