</pre>java encryption of the one-way encryption algorithm: Md5,sha,hmac. <p></p><p> MD5 encryption algorithm: </p><p></p><pre code_snippet_id= "1747607" snippet_ File_name= "blog_20160706_2_8502972" name= "code" class= "java" >/**
* MD5 encryption Algorithm
* *
@param data to encrypt
*
/public static byte[] Md5encrypt (byte[] data) {
byte[] b = null;
try {
MessageDigest MD = messagedigest.getinstance ("MD5");
Md.update (data);
b = md.digest ();
} catch (NoSuchAlgorithmException e) {
e.printstacktrace ();
}
return b;
}
Two, SHA encryption algorithm
/**
* SHA encryption Algorithm
* *
@param data to be encrypted by
/public static byte[] Shaencrypt (byte[] data) {
byte[] b = null;
try {
MessageDigest MD = messagedigest.getinstance ("SHA");
Md.update (data);
b = md.digest ();
} catch (NoSuchAlgorithmException e) {
e.printstacktrace ();
}
return b;
}
Three, HMAC encryption algorithm
HMAC (hash messages authentication code, hash message discriminator, authentication protocol based on the hash algorithm of the key). The principle of the authentication code is to use the public function and the key to produce a fixed length value as the authentication identification, and use this identity to identify the integrity of the message. Use a key to generate a fixed-size small block of data, the Mac, and add it to the message, and then transfer. The receiver uses the key that is shared with the sender to authenticate the identity.
3.1. Initialize secret key
/**
* Initialize HMAC secret
*
* @return/Public
static string Inihmackey () {
string key = "";
try {
Keygenerator keygenerator = keygenerator.getinstance (Hmac_key);
Secretkey Secretkey = Keygenerator.generatekey ();
Base64encoder encoder = new Base64encoder ();
Key = Encoder.encode (secretkey.getencoded ());
} catch (NoSuchAlgorithmException e) {
e.printstacktrace ();
}
Return key;
}
3.2. Encrypt data with HMAC's secret key
/**
*
@param data Encryption
* @param key key
* @return
/public
static byte[] Hmacencrypt (byte[] Dat A, String key) {
Secretkey secretkey = new Secretkeyspec (BASE64D (key), hmac_key);
Byte[] b = null;
try {
Mac Mac = Mac.getinstance (Secretkey.getalgorithm ());
Mac.init (Secretkey);
b = mac.dofinal (data);
} catch (NoSuchAlgorithmException e) {
e.printstacktrace ();
} catch (InvalidKeyException e) {
E.printstacktrace ();
}
return b;
}