Java URL Encryption decryption solution (turn)

Source: Internet
Author: User
Tags base64 decrypt

Using:

Java.net.URLEncoder.encode (BASE64 encoding (cryptographic strings), Stringcode) is used to encrypt the parameters in the URL.

let's start by saying how to encrypt.

one, the choice of algorithms:

For the process of encrypting a parameter in a URL, I do not recommend using cryptographic algorithms such as RSA or Triple DES, mainly because performance and speed are affected.

I suggest that you use symmetric encryption such as DES or PBE algorithm.

We use Pbewithmd5anddes here to implement encryption.

second, the principle of encryption

For a plain text, encrypted it will become a heap of garbled, this heap garbled contains a lot of illegal characters, we do not want to put these characters into the bean, so after the encryption, we also want to encrypt the results of Base64 encoding.

PBE literally, it must use a password, we do not want our encryption is too complex and affect the speed of the page jump, so we do not use the form of password +key, our side of the password is our key.

therefore:

Our entire encryption process is implemented as follows:

Input password (KEY)--> encrypted text--> to base64 the encrypted result encoded--> java.net.URLEncoder.encode encoded in a form that the browser can recognize--> transmit to the accepted action

And the decryption process is as follows:

The accepted action gets the parameter--> to decode the result base64--> get the Pure encrypted text--> decrypt--> get the decrypted value

Third, BASE64

This side of the principle of BASE64 said, only to realize that the current online there are many ways to achieve, have their own written, useful sun.misc.*, we will use in this example javax.mail.internet.MimeUtility A Base64 coding tool with its own.

two packages of Activation.jar and Mail.jar need to be introduced . The following are the specific implementations:

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;
&N Bsp; 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) {
}
}
}
}

implementation of encryption and decryption tool class

With the BASE64 tool class, the following work will become simple, write our cryptographic 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 =;

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 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);
}
}

Notice the three places that are bold above:

private final static int iterations =;

The higher the value, the deeper the encryption, the general example of the "Java Security Programming Guide" in the case of the value of the example, set to 1000, we only need 20 here is enough, the reason is to consider the speed of encryption and decryption.

int saltlength = 12;
This is base64 after decoding the length of the salt, after encryption after the BASE64 code after the length of the salt for the 8,base64 decoding of the length of the salt is 12, as for why, this is based on the principle of BASE64, can see the BASE64 principle, a lot of online, said also very simple.

Pbewithmd5anddes

We are using 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);
}
}

}

The specific use of tools in struts action

    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);

encode in the JSP page

Put the above bean into the request and take it to the next JSP page, which is processed on the JSP page 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 Current Process </span></u></a>

decrypt the encrypted value in the action that accepts the encryption parameter

We assume that our accepted action is: Querymytask.do, which accepts a series of parameters, in which the Processdefid and Processimgpath are encrypted.

Implemented as follows:

String Processimgfilepath = "";
String Processdefinitionid = (string) request.getparameter ("Processdefinitionid");
Processimgfilepath = (String) request.getparameter ("Processimgpath");

Processdefinitionid = Encrypturlpara.decrypt (Processdefinitionid);
Processimgfilepath = Encrypturlpara.decrypt (Processimgfilepath);

It should be noted that there is no need for decode here.

Eight, the key (password) storage

Because our key here is the password, is a text, we store it in the server side of the properties, of course, we are also encrypted storage.

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

We have a properties file, where:

Security.des.key=enc (Olo0lqeluulovrectdnghangmczwuyug)

This is the keywe used in the encrypt and decrypt methods.

We do not want this key to be in the form of clear text in properties, and we are also pbewithmd5anddesfor the key once again, of course, because of spring because of the Jasypt package, So this process is all automatic.

We use the Encrypt.bat tool from the bin under the Jasypt package:

Encrypt input=MyKey password=secret algorithm=

The command will output a line of garbled, this line of garbled copy to the properties file, the outer layer plus ENC (), such as:

Build: Olo0lqeluulovrectdnghangmczwuyug

Add properties to be converted into: ENC (Olo0lqeluulovrectdnghangmczwuyug)

Then an environmental change is required on the machine of the engineering department, such as:

Set App_encryption_password=secret The value here must be the same as the value after the password= on the Encrypt.bat command line above.

(Linux please use export App_encryption_password=secret)

Then configure spring so that the properties are automatically decrypted when the project is load by the app container, so that when we get to the key directly in our method, it's already clear (the decryption process is jasypt+spring), and here's what this step-by-step configuration is about:

<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'll is 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>

<!--
Configurer that replaces ${...} placeholders with the values from a
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"/>

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

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.