1. MD5 encryption, often used to encrypt user name passwords, when the user is authenticated.
protected byte[] encrypt(byte[] obj) ...{
try ...{
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(obj);
return md5.digest();
} catch (NoSuchAlgorithmException e) ...{
e.printStackTrace();
}
}
2. Sha encryption, similar to the use of MD5, but the two algorithms are different.
protected byte[] encrypt(byte[] obj) ...{
try ...{
MessageDigest sha = MessageDigest.getInstance("SHA");
sha.update(obj);
return sha.digest();
} catch (NoSuchAlgorithmException e) ...{
e.printStackTrace();
}
}
3. RSA encryption, RAS encryption allows decryption. Often used for encryption of text content.
import Java.security.KeyPair;
import Java.security.KeyPairGenerator;
import Java.security.interfaces.RSAPrivateKey;
import Java.security.interfaces.RSAPublicKey;
import Javax.crypto.Cipher;
/** *//**
* <b>RSAEncrypt</b>
* <p>
* @author Maqujun
* @see
*/
public class Rsaencrypt ... {
/** *//**
* Main method for Rsaencrypt.
* @param args
*/
public static void Main (string[] args) ... {
Try ... {
Rsaencrypt encrypt = new Rsaencrypt ();
String encrypttext = "Encrypttext";
keypairgenerator Keypairgen = keypairgenerator.getinstance ("RSA");
keypairgen.initialize (1024);
KeyPair KeyPair = Keypairgen.generatekeypair ();
//Generate keys
Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate ();
Rsapublickey PublicKey = (rsapublickey) keypair.getpublic ();
Byte[] e = Encrypt.encrypt (PublicKey, Encrypttext.getbytes ());
byte[] de = Encrypt.decrypt (privatekey,e);
System.out.println (encrypt.bytestostring (e));
System.out.println (encrypt.bytestostring (DE));
} catch (Exception e) ... {
E.printstacktrace ();
}
}
/** *//**
* Change byte array to String.
* @return byte[]
*/
protected String bytestostring (byte[] encrytpbyte) ... {
String result = "";
for (Byte bytes:encrytpbyte) ... {
result + = (char) bytes.intvalue ();
}
return result;
}
/** *//**
* Encrypt String.
* @return byte[]
*/
Protected byte[] Encrypt (Rsapublickey publickey, byte[] obj) ... {
if (publickey!= null) ... {
Try ... {
Cipher Cipher = cipher.getinstance ("RSA");
Cipher.init (Cipher.encrypt_mode, PublicKey);
return cipher.dofinal (obj);
} catch (Exception e) ... {
E.printstacktrace ();
}
}
return null;
}
/** *//**
* Basic Decrypt Method
* @return byte[]
*/
protected byte[] Decrypt (Rsaprivatekey privatekey, byte[] obj) ... {
if (privatekey!= null) ... {
Try ... {
Cipher Cipher = cipher.getinstance ("RSA");
Cipher.init (Cipher.decrypt_mode, Privatekey);
return cipher.dofinal (obj);
} catch (Exception e) ... {
E.printstacktrace ();
}
}
return null;
}
}