java各种加密

2017-11-02  本文已影响0人  jasonlu1208

importorg.apache.commons.codec.binary.Base64;

importjavax.crypto.KeyGenerator;

importjavax.crypto.Mac;

importjavax.crypto.SecretKey;

importjavax.crypto.spec.SecretKeySpec;

importjava.math.BigInteger;

importjava.security.InvalidKeyException;

importjava.security.MessageDigest;

importjava.security.NoSuchAlgorithmException;

/**

*@authorjasonLu

*@date2017/11/2 12:44

*@Description:

*/

public classMyEncrypt{

public static finalStringKEY_SHA="SHA";

public static finalStringKEY_MD5="MD5";

public static finalStringKEY_MAC="HmacMD5";

// sun不推荐使用它们自己的base64,用apache的挺好

/**

* BASE64解密

*/

public static byte[]decryptBASE64(byte[]dest) {

if(dest==null) {

return null;

}

returnBase64.decodeBase64(dest);

}

/**

* BASE64加密

*/

public static byte[]encryptBASE64(byte[]origin) {

if(origin==null) {

return null;

}

returnBase64.encodeBase64(origin);

}

/**

* MD5加密

*

*@throwsNoSuchAlgorithmException

*/

public static byte[]encryptMD5(byte[]data)

throwsNoSuchAlgorithmException{

if(data==null) {

return null;

}

MessageDigestmd5=MessageDigest.getInstance(KEY_MD5);

md5.update(data);

returnmd5.digest();

}

/**

* SHA加密

*

*@throwsNoSuchAlgorithmException

*/

public static byte[]encryptSHA(byte[]data)

throwsNoSuchAlgorithmException{

if(data==null) {

return null;

}

MessageDigestsha=MessageDigest.getInstance(KEY_SHA);

sha.update(data);

returnsha.digest();

}

/**

*初始化HMAC密钥

*

*@throwsNoSuchAlgorithmException

*/

public staticStringinitMacKey()throwsNoSuchAlgorithmException{

KeyGeneratorkeyGenerator=KeyGenerator.getInstance(KEY_MAC);

SecretKeysecretKey=keyGenerator.generateKey();

return newString(encryptBASE64(secretKey.getEncoded()));

}

/**

* HMAC加密

*

*@throwsNoSuchAlgorithmException

*@throwsInvalidKeyException

*/

public static byte[]encryptHMAC(byte[]data,Stringkey)

throwsNoSuchAlgorithmException,InvalidKeyException{

SecretKeysecretKey=newSecretKeySpec(decryptBASE64(key.getBytes()),

KEY_MAC);

Macmac=Mac.getInstance(secretKey.getAlgorithm());

mac.init(secretKey);

returnmac.doFinal(data);

}

public static voidmain(String[]args)throwsException{

Stringdata="test123456";

System.out.println(newBigInteger(encryptBASE64(data.getBytes())).toString(16));

System.out.println(newBigInteger(encryptBASE64(data.getBytes())).toString(32));

System.out.println(newString(decryptBASE64(encryptBASE64(data.getBytes()))));

System.out.println(newBigInteger(encryptMD5(data.getBytes())).toString());

System.out.println(newBigInteger(encryptSHA(data.getBytes())).toString());

System.out.println(newBigInteger(encryptHMAC(data.getBytes(),initMacKey())).toString());

}

}

上一篇下一篇

猜你喜欢

热点阅读