1. MD5 encryption, which is often used to encrypt user names and passwords.
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 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. It is often used for text content encryption.
Import java. Security. keypair;
Import java. Security. keypairgenerator;
Import java. Security. Interfaces. rsw.vatekey;
Import java. Security. Interfaces. rsapublickey;
Import javax. crypto. cipher ;/***//**
* Rsaencrypt
*
* @ 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 = keypairgen. generatekeypair ();
// Generate Keys
Rsw.vatekey privatekey = (rsw.vatekey) 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 (rsw.vatekey 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;
}
}