I wrote a small program for encryption and decryption to share with you.
Public class testencrypt {
/**
* Todo <method comments>
*
* @ Param ARGs
* @ Author yinpengbo, 04:35:12
* @ Modified
*/
// Key generator
Private keygenerator keygen;
// Stores the key
Private secretkey skey;
// Encryption and decryption tools
Private cipher c;
// Stores encryption results
Private byte [] cipherbyte;
Public testencrypt (){
Security. addprovider (new COM. Sun. crypto. provider. sunjce ());
Try {
// Obtain the key generator object
Keygen = keygenerator. getinstance ("des ");
// Generate the key
Skey = keygen. generatekey ();
// Generate cipher object
C = cipher. getinstance ("des ");
} Catch (exception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
/**
*
* Construction a new instance. Todo <something.>
*
* @ Param encryptmodel: for example, DES and AES
*/
Public testencrypt (string encryptmodel ){
Security. addprovider (new COM. Sun. crypto. provider. sunjce ());
Try {
// Obtain the key generator object
Keygen = keygenerator. getinstance (encryptmodel );
// Generate the key
Skey = keygen. generatekey ();
// Generate cipher object
C = cipher. getinstance (encryptmodel );
} Catch (exception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
/**
* Encrypt strings
* Todo <method comments>
*
* @ Param STR the string to be encrypted
* @ Return
* @ Author yinpengbo, 02:57:07, 2011-1-11
* @ Modified
*/
Public String createencryptor (string Str ){
// Use the key to initialize the cipher. The specified method is currently encrypted.
Try {
C. INIT (Cipher. encrypt_mode, skey );
// Encrypted Storage
Cipherbyte = C. dofinal (Str. getbytes ());
// Convert byte to string using base64 encode
String encode = base64.encode (cipherbyte );
Return encode;
} Catch (exception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
Return "";
}
}
/**
* Decryption
* Todo <method comments>
*
* @ Param buff, encrypted byte
* @ Return
* @ Author yinpengbo, 03:03:04, 2011-1-11
* @ Modified
*/
Public String createdencryptor (string passstr ){
Try {
// Initialize cipher, which is specified as decryption currently
C. INIT (Cipher. decrypt_mode, skey );
// Convert string to byte using the decode method of base64
Byte [] bytes = base64.decode (passstr );
Cipherbyte = C. dofinal (bytes );
Return new string (cipherbyte );
} Catch (exception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
Return "";
}
}
Public static void main (string [] ARGs ){
Testencrypt TE = new testencrypt ("AES ");
String teststr = "tom123 & id = Yin pengbo ***...... &...... & Amp; 1324 ";
System. Out. println ("before encryption:" + teststr );
String afterencryptstr = tE. createencryptor (teststr );
System. Out. println ("encrypted:" + afterencryptstr );
System. Out. println ("decrypted:" + Te. createdencryptor (afterencryptstr ));