import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class EncodeTest { private String encodeMd5(String src) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(src.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); return fromBytesToHex(byteArray); } private String encodeDes(String src, String password) throws Exception { SecretKey secretKey = new SecretKeySpec(password.getBytes(), "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] dist = cipher.doFinal(src.getBytes("utf-8")); return fromBytesToHex(dist); } public static byte[] initKey() throws NoSuchAlgorithmException { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); return secretKey.getEncoded(); } public String encodeAes(String src, byte[] key) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherBytes = cipher.doFinal(src.getBytes()); return fromBytesToHex(cipherBytes); } public static String fromBytesToHex(byte[] resultBytes) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < resultBytes.length; i++) { if (Integer.toHexString(0xFF & resultBytes[i]).length() == 1) { builder.append("0").append( Integer.toHexString(0xFF & resultBytes[i])); } else { builder.append(Integer.toHexString(0xFF & resultBytes[i])); } } return builder.toString(); } public static void main(String[] args) throws Exception { EncodeTest et = new EncodeTest(); String password = "helloword"; String result = et.encodeMd5(password); System.out.println(result); System.out.println(et.encodeDes(password, "Bye-2016")); byte[] aesKey = et.initKey(); System.out.println(et.encodeAes(password, aesKey)); } }
运行结果
59284aa85709ddaf3bd246030060f6a2 049db4281b51b198bb26fffbb040fde1 c6693135b2179504ad3d59ac930fb278