1. MD5 is not described here. For details, refer to subsequent articles.
2. DES data encryption:
Import java. io. UnsupportedEncodingException;
Import java. security. SecureRandom;
Import javax. crypto. Cipher;
Import javax. crypto. SecretKey;
Import javax. crypto. SecretKeyFactory;
Import javax. crypto. spec. DESKeySpec;
Public class test
{
Public static void main (String [] args)
Throws UnsupportedEncodingException
{
// Content to be encrypted
String str = "I am a Chinese ";
// Password, which must be a multiple of 8
String password = "alnton08 ″;
Byte [] result = desCrypto (str. getBytes (), password );
System. out. println ("encrypted content:" + new String (result ));
// Decrypt the above content directly
Try
{
Byte [] decryResult = decrypt (result, password );
System. out. println ("pre-encryption content:" + new String (decryResult ));
}
Catch (Exception e1)
{
E1.printStackTrace ();
}
}
/**
* <对字符串进行des加密,将字符串转化为字节数组解密>
*/
Public static byte [] desCrypto (byte [] datasource, String password)
{
Try
{
SecureRandom random = new SecureRandom ();
DESKeySpec export ey = new DESKeySpec (password. getBytes ());
// Create a key factory and use it to convert the keyspec
SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES ");
SecretKey securekey = keyFactory. generateSecret (secret ey );
// The Cipher object actually completes the encryption operation
Cipher cipher = Cipher. getInstance ("DES ");
// Use the key to initialize the Cipher object
Cipher. init (Cipher. ENCRYPT_MODE, securekey, random );
// Now, obtain and encrypt the data
// Perform the encryption operation
Return cipher. doFinal (datasource );
}
Catch (Throwable e)
{
E. printStackTrace ();
}
Return null;
}
/**
* <将加密的密文字节数组转化为明文字节数组>
*/
Public static byte [] decrypt (byte [] src, String password)
Throws Exception
{
// The DES algorithm requires a trusted random number Source
SecureRandom random = new SecureRandom ();
// Create a receiveyspec object
DESKeySpec export ey = new DESKeySpec (password. getBytes ());
// Create a key Factory
SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES ");
// Convert the receiveyspec object to a SecretKey object
SecretKey securekey = keyFactory. generateSecret (secret ey );
// The Cipher object actually completes the decryption operation
Cipher cipher = Cipher. getInstance ("DES ");
// Use the key to initialize the Cipher object
Cipher. init (Cipher. DECRYPT_MODE, securekey, random );
// Start decryption
Return cipher. doFinal (src );
}
}