E-Commerce uses data encryption to protect databases (2)

Source: Internet
Author: User
Tags array to string
E-Commerce uses data encryption to protect databases (2)
I explained some theoretical content in the previous article. This time we will introduce the example in detail:

For example, we create a class desutil. Java

As mentioned last time, I need to create a key first, so I need to add a method to create the des key first. For ease of use, we temporarily write all the methods as static methods.
// Filename is the file path to save
Public static void createkey (string filename) throws exception {
// Generate a trusted random number Source
Securerandom sr = new securerandom ();
// Generate a keygenerator object for the selected DES algorithm
Keygenerator kg = keygenerator. getinstance ("des ");
Kg. INIT (SR );
// Generate the key
Key key = kg. generatekey ();
// Save the key data as a file for future use
Writefile (Key, filename); // description later
}

Now, we can use the above method to generate a key.
Because we may call encryption or decryption methods in different places, we must store the generated key in a file, it is recommended to store it to a directory of the application's/WEB-INF/, because that directory is called only by its own program and cannot be accessed through the URL, so it is safer. Next, we need to write two methods: one is to store the key to a file, and the other is to read the key in the encryption or decryption method for encryption or decryption.

// Filename is the key storage path, and MSG is the key generated in the first method.
Public static void writefile (Key MSG, string filepath ){
Try {
File file = new file (filepath );
If (file. exists ()){
File. Delete ();
}
Fileoutputstream WF = new fileoutputstream (File );
Objectoutputstream out = new objectoutputstream (WF );
Out. writeobject (MSG );
Out. Close ();
File = NULL;
WF = NULL;
} Catch (ioexception e ){
Debug (E. getmessage ());
}
}
// Filename is the key storage path
Public static key readfile (string filepath ){
Key key = NULL;
Try {
File F = new file (filepath );
If (F. exists ()){
Fileinputstream BW = new fileinputstream (f );
Objectinputstream in = new objectinputstream (BW );
Key = (key) in. readobject ();
In. Close ();
BW = NULL;
}
F = NULL;
} Catch (exception e ){
Debug (E. getmessage ());
}
Return key;
}

Here we directly store the key object in a file. Of course, the key object can also be stored in bytes, but it may be a little troublesome!

Now the key problem has been solved. The next step is to write encryption and solve the problem.

// STR byte array to be encrypted
Public static byte [] dataencrypt (byte [] STR, string filename) throws exception {
//
Secretkey key = (secretkey) readfile (filename );
// 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, key );
// Perform the encryption operation
Byte [] encrypteddata = cipher. dofinal (STR );
//
Return encrypteddata;
}
// STR byte array to be decrypted
Public static byte [] datadecrypt (byte [] STR, string filename) throws exception {
//
Secretkey key = (secretkey) readfile (filename );
// The cipher object actually completes the encryption operation
Cipher cipher = cipher. getinstance ("des ");
// Use the key to initialize the cipher object
Cipher. INIT (Cipher. decrypt_mode, key );
// Perform the encryption operation
Byte [] encrypteddata = cipher. dofinal (STR );
//
Return encrypteddata;
}

Simple: We have successfully created the DES encryption and decryption class. Test it!

Public static void main (string [] ARGs ){
String filename = "C:/DES. Key ";
String STR = "0109103746028 ";
System. Out. Print ("Source =" + Str );
Try {
Desutil. createkey (filename );
//
Byte [] enstr = desutil. dataencrypt (Str. getbytes (), filename );
STR = new string (enstr); // encrypted string
System. Out. Print ("encrypt =" + Str );
//
Byte [] destr = desutil. datadecrypt (Str. getbytes (), filename );
STR = new string (destr); // decrypted string
System. Out. Print ("decrypt =" + Str );
} Catch (exception e ){
E. printstacktrace ();
}
Debug ("OK ");
}

If there is no definite error, it must be reported: javax. crypto. badpaddingexception: given final block not properly padded
What's going on? It's all written according to you. Why is it wrong? After careful analysis, it is not difficult to find that the exception is thrown during decryption and the encryption method is correct.

However, the only difference between the two methods is that the cipher object mode is different, which eliminates the possibility of program errors. Let's take a look at the information about the exception. The approximate meaning is that the provided block does not meet the requirements. What does that mean ??? It turns out that when des is used for encryption, if the last bit is less than 64 characters in length, it will be automatically filled with 64 characters. So during the conversion from byte array to string, the invisible characters it fills can be changed, so the system throws an exception. How can I solve the problem? We still remember that in mail transmission, we usually save some information encoding. By the way, it is base64, which ensures the information integrity, so we just use the token. For ease of use, let's write a new method to encapsulate the original method:
//
Public static string dataencrypt (string Str ){
String encrypt = NULL;
Try {
Byte [] ret = dataencrypt (Str. getbytes ("UTF-8"), filename );
Encrypt = new string (base64.encode (RET), "UTF-8 ");
} Catch (exception e ){
System. Out. Print (E );
Encrypt = STR;
}
Return encrypt;
}
//
Public static string datadecrypt (string Str ){
String decrypt = NULL;
Try {
Byte [] ret = datadecrypt (base64.decode (Str. getbytes ("UTF-8"), filename );
Decrypt = new string (Ret, "UTF-8 ");
} Catch (exception e ){
System. Out. Print (E );
Decrypt = STR;
}
Return decrypt;
}

We changed the parameters of the method to a string, but why use UTF-8? Cannot I specify its byte format without specifying it? As we all know, UTF-8 is a universal character encoding, with it to transmit any string will not be a problem, through it can also be perfect to solve the problem of J2EE Chinese! So we 'd better use UTF-8 encoding to reduce unnecessary trouble.

Note: When an exception is thrown during encryption or decryption in the preceding method, the original value is returned, making it easier to locate errors when the method fails to be called.

You can also use other keys to encrypt and decrypt data in different places?

Summary: des is a relatively old encryption algorithm, which is not currently the safest. Therefore, you can use other encryption algorithms for encryption and decryption to obtain a safer system.

Appendix: source files of desutil. Java and base64.java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.