Java URL encryption and decryption solution)

Source: Internet
Author: User

Use:

 

Java.net. urlencoder. encode (base64 encoding (encrypted string), stringcode) to encrypt parameters in the URL.

 

First, let's talk about encryption.

 

1. algorithm selection:

 

For the process of encrypting parameters in a URL, I do not recommend using encryption algorithms such as RSA or triple DES, mainly because the performance and speed will be affected.

 

I suggest you use symmetric encryption algorithms such as des or PBE.

 

We will use it herePbewithmd5anddesTo implement encryption.

 

Ii. Encryption principles

 

For a plain text, after encryption, it will become a bunch of garbled characters, which include many illegal characters. We do not want to put these characters into the bean, so after encryption, we also need to perform base64 encoding on the encrypted results.

 

PBE literally understands that it must use a password. We do not want our encryption to be too complex and affect the page Jump speed,Therefore, we do not use a password + key. The password on our side is our key..

 

Therefore:

 

The entire encryption process is implemented as follows:

 

Enter the password (key) --> encrypted text --> encode the encrypted result with base64 --> Use java.net. urlencoder. encode is encoded into a form that the browser can recognize --> transmitted to the accepted action

 

The decryption process is as follows:

 

The accepted action gets the parameter --> decodes the result with base64 --> obtains the encrypted text --> decrypts --> obtains the decrypted value.

 

Iii. base64

I will not talk much about the base64 principle here. I just want to talk about implementation. Currently there are many implementation methods on the Internet, which are self-written and useful for sun. Misc. *. We will use it in this example.Javax. Mail. Internet. mimeutilityThe built-in base64 encoding tool.

Activation. jar and mail. Jar packages need to be introduced.. The specific implementation is as follows:

Import javax. Mail. Internet. mimeutility;

Public class base64 {
Public static byte [] encode (byte [] B) throws exception {
Bytearrayoutputstream baos = NULL;
Outputstream b64os = NULL;
Try {
Baos = new bytearrayoutputstream ();
B64os = mimeutility. encode (baos, "base64 ");
B64os. Write (B );
B64os. Close ();
Return baos. tobytearray ();
} Catch (exception e ){
Throw new exception (E );
} Finally {
Try {
If (baos! = NULL ){
Baos. Close ();
Baos = NULL;
}
} Catch (exception e ){
}
Try {
If (b64os! = NULL ){
B64os. Close ();
B64os = NULL;
}
} Catch (exception e ){
}
}
}

Public static byte [] Decode (byte [] B) throws exception {
Bytearrayinputstream BAIS = NULL;
Inputstream b64is = NULL;
Try {
BAIS = new bytearrayinputstream (B );
B64is = mimeutility. Decode (BAIS, "base64 ");
Byte [] TMP = new byte [B. Length];
Int n = b64is. Read (TMP );
Byte [] res = new byte [N];
System. arraycopy (TMP, 0, res, 0, N );

Return res;
} Catch (exception e ){
Throw new exception (E );
} Finally {
Try {
If (BAIS! = NULL ){
BAIS. Close ();
BAIS = NULL;
}
} Catch (exception e ){
}
Try {
If (b64is! = NULL ){
B64is. Close ();
B64is = NULL;
}
} Catch (exception e ){
}
}
}
}

 

IV. Implementation of encryption and decryption tools

 

With the base64 tool class, the following work will become simple. compile our encryption and decryption tool class:

 

Import java. Io. dataoutputstream;
Import java. Io. fileoutputstream;
Import java. Security .*;
Import javax. crypto .*;
Import javax. crypto. spec .*;

Import java. util .*;

Import org. Apache. commons. Logging. log;
Import org. Apache. commons. Logging. logfactory;

Public class securityhelper {
Protected final static log logger = logfactory. getlog (securityhelper. Class );
Private Final Static int iterations = 20;

Public static string encrypt (string key, string plaintext) throws exception {
String encrypttxt = "";
Try {
Byte [] salt = new byte [8];
Messagedigest MD = messagedigest. getinstance ("MD5 ");
Md. Update (key. getbytes ());
Byte [] digest = md. Digest ();
For (INT I = 0; I <8; I ++ ){
Salt [I] = digest [I];
}
Pbekeyspec = new pbekeyspec (key. tochararray ());
Secretkeyfactory keyfactory = secretkeyfactory
. Getinstance ("Pbewithmd5anddes");
Secretkey skey = keyfactory. generatesecret (pbekeyspec );
Pbeparameterspec paramspec = new pbeparameterspec (salt, iterations );
Cipher cipher = cipher. getinstance ("Pbewithmd5anddes");
Cipher. INIT (Cipher. encrypt_mode, skey, paramspec );
Byte [] ciphertext = cipher. dofinal (plaintext. getbytes ());
String saltstring = new string (base64.encode (SALT ));
String ciphertextstring = new string (base64.encode (ciphertext ));
Return saltstring + ciphertextstring;
} Catch (exception e ){
Throw new exception ("encrypt text error:" + E. getmessage (), e );
}
}

Public static string decrypt (string key, string encrypttxt)
Throws exception {
 Int saltlength = 12;
Try {
String salt = encrypttxt. substring (0, saltlength );
String ciphertext = encrypttxt. substring (saltlength, encrypttxt
. Length ());
Byte [] saltarray = base64.decode (salt. getbytes ());
Byte [] ciphertextarray = base64.decode (ciphertext. getbytes ());
Pbekeyspec keyspec = new pbekeyspec (key. tochararray ());
Secretkeyfactory keyfactory = secretkeyfactory
. Getinstance ("Pbewithmd5anddes");
Secretkey skey = keyfactory. generatesecret (keyspec );
Pbeparameterspec paramspec = new pbeparameterspec (saltarray,
Iterations );
Cipher cipher = cipher. getinstance ("Pbewithmd5anddes");
Cipher. INIT (Cipher. decrypt_mode, skey, paramspec );
Byte [] plaintextarray = cipher. dofinal (ciphertextarray );
Return new string (plaintextarray );
} Catch (exception e ){
Throw new exception (E );
}
}

 

Note:

Private Final Static int iterations = 20;

 

The larger the value above, the deeper the encryption, the general examples are based on the value of the example in the "Java security programming guide" book, set to 1000, we only need 20 here, the reason is the speed of encryption and decryption.

Int saltlength = 12;
This is the length of the salt after base64 decoding. After base64 encoding, the length of the salt is 8, and the length of the salt after base64 decoding is 12. Why, this is also based on the base64 principle. For details, we can refer to the base64 principle. There are many online topics, which are also simple.

 

Pbewithmd5anddes

We use pbewithmd5anddes encryption.

 

Write a test class below

Public static void main (string [] ARGs ){
String encrypttxt = "";
String plaintxt = "Hello oh my god ";
Try {
System. Out. println (plaintxt );
Encrypttxt = encrypt ("mypassword01", plaintxt );
Plaintxt = decrypt ("mypassword01", encrypttxt );
System. Out. println (encrypttxt );
System. Out. println (plaintxt );
} Catch (exception e ){
E. printstacktrace ();
System. Exit (-1 );
}
}

}

 

5. Use of tool classes in struts actions

Mytaskdto taskdto = new mytaskdto ();
Taskinstance Ti = (taskinstance) it. Next ();
Taskdto. settaskname (TI. getname ());
Taskdto. settaskcreatedate (SD. Format (TI. getcreate ()));
Taskdto. settaskdescr (TI. getdescription ());
/* No encrypted data */
String taskid = string. valueof (TI. GETID ());
String tokenid = string. valueof (TI. gettoken (). GETID ());
Processimgname = propertyutil. getproperty (
Constants. bpm_process_payment_processimage). tostring ()
+ ". Jpg ";
Processdefid = string. valueof (TI. gettoken ()
. Getprocessinstance (). getprocessdefinition (). GETID ());

/* Encrypted data */
Taskid = encrypturlpara. Encrypt (taskid );
Tokenid = encrypturlpara. Encrypt (tokenid );
Processimgname = encrypturlpara. Encrypt (processimgname );
Processdefid = encrypturlpara. Encrypt (processdefid );

Taskdto. settaskid (taskid );
Taskdto. settokenid (tokenid );
Taskdto. setprocessdefinitionid (processdefid );
Taskdto. setprocessimagename (processimgname );

 

6. encode on the JSP page

Put the above bean into the request and take it to the next JSP page. The processing on the JSP page is as follows:

String processimgpath = taskdto. getprocessimagename ();
String processdefid = taskdto. getprocessdefinitionid ();
Processimgpath = java.net. urlencoder. encode (processimgpath, "UTF-8 ");
Processdefid = java.net. urlencoder. encode (processdefid, "UTF-8 ");
String showprocessimgurl = request. getcontextpath () + "/querymytask. Do ";

<A href = "<% = showprocessimgurl %>? Method = showprocessimg& Processdefinitionid = <% = processdefid %> & processimgpath = <% = processimgpath %>"Target =" _ blank "> <u> <SPAN class =" left_txt "> view the current process </span> </u> </a>

7. decrypt the encrypted value in the action that accepts the encrypted Parameter

Assume that the accepted action is querymytask. Do. It accepts a series of parameters. In the base, processdefid and processimgpath are encrypted.

The implementation is as follows:

String processimgfilepath = "";
String processdefinitionid = (string) request. getparameter ("processdefinitionid ");
Processimgfilepath = (string) request. getparameter ("processimgpath ");

 Processdefinitionid = encrypturlpara. decrypt (processdefinitionid );
Processimgfilepath = encrypturlpara. decrypt (processimgfilepath );

Note that decode is not required here.

 

8. Key (password) Storage

 

Because the key here is a password, it is a text, and we store it in the properties of the server. Of course, we also store it encrypted.

 

We use spring + jasypt1.5 (Java simple encrypt package ).

 

We have a properties file, where:

Security. Des. Key = ENC (olo0lqelulovrectdnghangmczwuyug)

This is what we use in the encrypt and decrypt methods.Key.

We do not want this key to be stored in properties in plain text. The key is also encrypted once again.Pbewithmd5anddesOf course, because Spring has the jasypt package, this process is automatic.

We use the built-in encrypt. Bat tool in the bin under the jasypt package:

 

Encrypt input =MykeyPassword =SecretAlgorithm =Pbewithmd5anddes

This command will output a line of Garbled text, copy this line of Garbled text to the properties file, and add ENC () to the outer layer, such:

 

Generation:Olo0lqelulovrectdnghangmczwuyug

After adding properties, You need to convert it:ENC (olo0lqelulovrectdnghangmczwuyug)

Then, you need to set up an environment change on the machines deployed in the project, such:

Set app_encryption_password = secret the value here must be the same as the value after Password = in the above encrypt. Bat command line.

(Use Export app_encryption_password = secret for Linux)

 

Then configure spring so that the properties will be automatically decrypted when the project is loaded by the app container, in this way, when the key is obtained directly in our method, it is already in plain text (the decryption process is automatically completed by jasypt + spring). The following is the detailed configuration of this step:

 

<Context: component-scan base-package = "jbpmweb"/>
<Bean id = "environmentvariablesconfiguration"
Class = "org. jasypt. Encryption. PBE. config. environmentstringpbeconfig"
P: algorithm ="Pbewithmd5anddes"P: passwordenvname =" app_encryption_password "/>

<! --
The will be the encryptor used for decrypting configuration values.
-->

<Bean id = "configurationencryptor" class = "org. jasypt. Encryption. PBE. standardpbestringencryptor"
P: config-ref = "environmentvariablesconfiguration"/>

<Bean id = "propertyconfigurer"
Class = "org. jasypt. Spring. properties. encryptablepropertyplaceholderconfigurer">
<Constructor-Arg ref = "configurationencryptor"/>
<Property name = "locations">
<List>
<Value> classpath: XXX. properties </value>
</List>
</Property>
</Bean>

<! --
Explorer that replaces $ {...} placeholders with values from
Properties File
-->
<Context: Property-placeholder location = "classpath: jbpmweb. properties"/>

<Bean id = "commonsconfigurationfactorybean" class = "XXX. XXX. commonsconfigurationfactorybean"
P: systempropertiesmodename = "system_properties_mode_override" P: encryptor-ref = "configurationencryptor">
<Constructor-Arg>
<Bean class = "org. Apache. commons. configuration. propertiesconfiguration">
<Constructor-Arg value = "XXX. properties"/>
</Bean>
</Constructor-Arg>
</Bean>
 

<Bean id = "propertiesconfiguration" factory-bean = "& amp; commonsconfigurationfactorybean"
Factory-method = "getconfiguration"/>

Address: http://blog.csdn.net/lifetragedy/article/details/6318017

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.