reduce the length of encrypted text
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Friday, December 21, 2007 06:31 AM

I have a struts application, where i am facing a peculiar problem. I have a Java bean class UserProfile implements Serializable { private Integer userId; private String email; private String hiddenPassword; } I am setting some value in to the "hiddenPassword" property of the bean (after encryption). The way i am encrypting it is shown below with the help of a utility method: UserProfile up = new UserProfile(); up.setUserId(123); up.setEmail("kssubin@gmail.com"); up.setHiddenPassword(encrypt("some sample text")); //utility methods for encrypti   More>>

I have a struts application, where i am facing a peculiar problem.


I have a Java bean

class UserProfile implements Serializable {

private Integer userId;

private String email;

private String hiddenPassword;

}


I am setting some value in to the "hiddenPassword" property
of the bean (after encryption).

The way i am encrypting it is shown below with the help of a utility method:


UserProfile up = new UserProfile();

up.setUserId(123);

up.setEmail("kssubin@gmail.com");

up.setHiddenPassword(encrypt("some sample text"));


//utility methods for encryption

public static String encrypt (String message) {

try {

java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");

return hex (md.digest(message.getBytes("CP1252")));

} catch (NoSuchAlgorithmException e) { logger.error(e);

} catch (UnsupportedEncodingException e) { logger.error(e);

}

return null;

}


private static String hex(byte[] array) {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < array.length; ++i) {

sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));

}

return sb.toString();

}




Also i have Velocity mail template where i have a placeholder for one

URL. once it reaches the template, its value will be like:


Ex:

http://localhost:8080/info/addPassword.do?dispatch=newPassword&

userEmail=f45yOJK123%w23BVu78fbhjYh56Kp&userid=eN867yLrG%2BFy1x1rFmG0hQ4yVk83wlzUuiFgi

V5xXJKfZIxRH9CIf5LOr3YWAKaH




It will be very lengthy and also



So before passing this URL value to velocity template, i am doing some processing, inside Struts Action class:



String host="http://localhost:8080";

String logoImgPath = servlet.getServletContext().getRealPath("/images/logo.gif");

String encryptedUrl = host +

"/info/addPassword.do?dispatch=newPassword&userEmail="+

URLEncrypter.encodeURL(URLEncrypter.encrypt(userProfile.getEmail()) + "&userId=" + userProfile.getUserId()));



Ref. UrlEncrypter class below(end).



I am passing this 'encrypedUrl' to a java.util.List, which will help me to access it from the

Velocity Template. I am getting that value in the Velocity

Template file as:



List args = new ArrayList();

args.add(0,encryptedUrl);

${arg.get(0)}



I am sending this Velocity Template as a mail, to the email-id specified in the UserProfile object.



This is how i send the email through the application:

String templFile = "consultant-add-advisor-password.vm";

String body = VelocityUtil.getEmailContentFromTemplateFile(args, templFile);



Also there is a utility method which sends the 'body' to the email-id specified

in the UserProfile object:



EmailUtil.sendHtmlFormattedMsg(from, to, subject, body, logoImgPath,replyTo);



So in the string 'body', the encryptedUrl will be there. This encryptedUrl

should be displayed a hyperlink in the mail. But as per my requirement it should display as

encryptedUrl text , as well as when we it should be a hyperlink.



So in the velocity template i have given some thing like this:



${arg.get(0)}



But when i do this, the hyperlink text will be the same as the value for the

hyperlink 'href' attribute. The person who gets the mail can copy the hyperlink

text and give it in the address bar of his browser, or he can directly

click the hyperlink. Both should work. But when the encrypted url is displayed

as a hyperlink text in the email, its comming in 3 lines, because of its length.



Ex:

http://localhost:8080/info/addPassword.do?dispatch=newPassword&

userEmail=f45yOJK123%w23BVu78fbhjYh56Kp&userid=eN867yLrG%2BFy1x1rFmG0hQ4yVk83wlzUuiFgi

V5xXJKfZIxRH9CIf5LOr3YWAKaH



And when the person tries to copy the text and pastes in in browser, sometimes all the 3 lines

won't be there in the address bar, only the first line is coming. That means

while copying only first line was move to clipboard.



So i want to know how can i reduce the length of the encrypted url, which needs to

placed in the velocity template, which will help me in displaying the whole

content in a single line. I am looking for a better way of encryption/decryption

which may solve this problem.





The URLEncrypter class is like this:

public class URLEncrypter {

private static final String PASS_PHRASE = "ABCDEFGH";

public static String encrypt(String msg){

try {

java.security.spec.KeySpec keySpec = new javax.crypto.spec.DESKeySpec(PASS_PHRASE.getBytes());

javax.crypto.SecretKey key = javax.crypto.SecretKeyFactory.getInstance("DES").generateSecret(keySpec);

javax.crypto.Cipher ecipher = javax.crypto.Cipher.getInstance(key.getAlgorithm());

ecipher.init(Cipher.ENCRYPT_MODE, key);

//Encode the string into bytes using utf-8

byte[] utf8 = msg.getBytes("UTF8");

//Encrypt

byte[] enc = ecipher.doFinal(utf8);

//Encode bytes to base64 to get a string

return new sun.misc.BASE64Encoder().encode(enc);

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (InvalidKeySpecException e) {

e.printStackTrace();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (IllegalStateException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return null;

}



public static String decrypt(String msg){

try {

KeySpec keySpec = new DESKeySpec(PASS_PHRASE.getBytes());

SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);

Cipher decipher = Cipher.getInstance(key.getAlgorithm());

decipher.init(Cipher.DECRYPT_MODE, key);

// Decode base64 to get bytes

byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(msg);

//Decrypt

byte[] utf8 = decipher.doFinal(dec);

//Decode using utf-8

return new String(utf8, "UTF8");

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (InvalidKeySpecException e) {

e.printStackTrace();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (IllegalStateException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

}

return null;

}



public static String encodeURL(String url){

try {

return URLEncoder.encode(url,"UTF-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return null;

}

}

   <<Less

Re: reduce the length of encrypted text

Posted By:   Robert_Lybarger  
Posted On:   Friday, December 21, 2007 09:00 AM

I didn't get through your whole question because you are using some wrong terminology, which makes things a little confusing to try to read any further. Nowhere are you "encrypting" anything. Early on, you are computing a "hash" (a message digest) for some string. That is not encryption, as encryption carries the implication the operation can be reversed. (A message digest cannot be.) Later on, you are simply base64-encoding some material. This is likewise not encryption: it is a simple scheme that ensures all the material can be displayed in a limited-bit-count character set (6-bit, IIRC) so it can be safely transferred as plain text, which us old-timers needed back when e-mail's effectiveness was limited to the displayable screen characters. That is also not encryption. Please be careful with the terminology. Note that, regardless, there will a proportional relationship between the length of encoded (or encrypted) material and the source material. So if you want the encoded values to be shorter, you'll have to start with shorter values. message digests, OTOH, tend to have a fixed length for any source material. What this comes down to, then, is that you might want to store information in a database table instead of in a set of encoded URL query string parameters. The database table entry should probably have some sort of a unique key applied to it, and this key should be what is sent to the user. Thus the URL will have a fixed and reasonable length to it regardless of the amount of material in the database that is "hidden" behind this key value. In your case, the primary key should probably *NOT* be sequential, just to keep curious people from phishing around for other people's info. This being said, what *may* work for the primary key is to compute a message digest for the info in the database table, and use this digest for the primary key (and in the URL query string parameter set).
HTH.
About | Sitemap | Contact