1 import java.math.BigInteger; 2 import java.security.InvalidKeyException; 3 import java.security.MessageDigest; 4 import java.security.NoSuchAlgorithmException; 5 import javax.crypto.KeyGenerator; 6 import javax.crypto.Mac; 7 import javax.crypto.SecretKey; 8 import javax.crypto.spec.SecretKeySpec; 9 import org.apache.commons.codec.binary.Base64; 10 11 public class MyEncrypt { 12 public static final String KEY_SHA = "SHA"; 13 public static final String KEY_MD5 = "MD5"; 14 public static final String KEY_MAC = "HmacMD5"; 15 16 17 // sun不推荐使用它们自己的base64,用apache的挺好 18 /** 19 * BASE64解密 20 */ 21 public static byte[] decryptBASE64(byte[] dest) { 22 if (dest == null) { 23 return null; 24 } 25 return Base64.decodeBase64(dest); 26 } 27 28 /** 29 * BASE64加密 30 */ 31 public static byte[] encryptBASE64(byte[] origin) { 32 if (origin == null) { 33 return null; 34 } 35 return Base64.encodeBase64(origin); 36 } 37 38 /** 39 * MD5加密 40 * 41 * @throws NoSuchAlgorithmException 42 */ 43 public static byte[] encryptMD5(byte[] data) 44 throws NoSuchAlgorithmException { 45 if (data == null) { 46 return null; 47 } 48 MessageDigest md5 = MessageDigest.getInstance(KEY_MD5); 49 md5.update(data); 50 return md5.digest(); 51 } 52 53 /** 54 * SHA加密 55 * 56 * @throws NoSuchAlgorithmException 57 */ 58 public static byte[] encryptSHA(byte[] data) 59 throws NoSuchAlgorithmException { 60 if (data == null) { 61 return null; 62 } 63 MessageDigest sha = MessageDigest.getInstance(KEY_SHA); 64 sha.update(data); 65 return sha.digest(); 66 } 67 68 /** 69 * 初始化HMAC密钥 70 * 71 * @throws NoSuchAlgorithmException 72 */ 73 public static String initMacKey() throws NoSuchAlgorithmException { 74 KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC); 75 SecretKey secretKey = keyGenerator.generateKey(); 76 return new String(encryptBASE64(secretKey.getEncoded())); 77 } 78 79 /** 80 * HMAC加密 81 * 82 * @throws NoSuchAlgorithmException 83 * @throws InvalidKeyException 84 */ 85 public static byte[] encryptHMAC(byte[] data, String key) 86 throws NoSuchAlgorithmException, InvalidKeyException { 87 SecretKey secretKey = new SecretKeySpec(decryptBASE64(key.getBytes()), 88 KEY_MAC); 89 Mac mac = Mac.getInstance(secretKey.getAlgorithm()); 90 mac.init(secretKey); 91 return mac.doFinal(data); 92 93 } 94 95 public static void main(String[] args) throws Exception { 96 // TODO Auto-generated method stub 97 String data = "简单加密"; 98 System.out.println(new BigInteger(encryptBASE64(data.getBytes())).toString(16)); 99 System.out.println(new BigInteger(encryptBASE64(data.getBytes())).toString(32)); 100 System.out.println(new String(decryptBASE64(encryptBASE64(data.getBytes())))); 101 102 System.out.println(new BigInteger(encryptMD5(data.getBytes())).toString()); 103 System.out.println(new BigInteger(encryptSHA(data.getBytes())).toString()); 104 105 System.out.println(new BigInteger(encryptHMAC(data.getBytes(), initMacKey())).toString()); 106 } 107 108 }