How to encrypt a password in a jsp

Hi everybody.

First I have a form with parameters “User” and “Pass” and I send them by post method to a jsp in which I read the User and Password, then look in the database if the User and Password matches, then I want to encrypt the Password and User and save EncryptedUser and EncryptedPassword in a Cookie, last I want to read the EncryptedUser and EncryptedPassword from the Cookie and decrypt them.
I just can’t do the Encryption and Decryption steps, so I’m asking you for a help.
I read somewhere in the internet I have to use a servlet for encrypting but I don’t know how to use it with my jsps.

In that case I found this servlet:


import java.io.UnsupportedEncodingException;
import javax.crypto.*;
import javax.swing.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EncryptDecrypt {
Cipher ecipher;
Cipher dcipher;

EncryptDecrypt(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);

} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}

public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");

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

// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}

public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

// Decrypt
byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}




public static void main(String[] args){
try{
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();

// Create encrypter/decrypter class
EncryptDecrypt encrypter = new EncryptDecrypt(key);

//Pass variable I should get from the form with the request.getParameter("Pass");
String Pass = "Password"; //Just to make it work

// Encrypt
String encrypted = encrypter.encrypt(Pass);

// Decrypt
String decrypted = encrypter.decrypt(encrypted);

// Output

System.out.println("Encrypted: "+encrypted);
System.out.println("Decrypted: "+decrypted);

} catch (Exception e) {
}
}
}

I hope you can help me and you can understand my not-good-english :slight_smile:

If there is any safer way to make a secure login just let me know :slight_smile:
Thanks a lot :slight_smile:

As you said

I just can’t do the Encryption and Decryption steps…
But the code you provided is working fine and does the Encryption-Decryption. So what do you want to do more?

I personally use MD5, you can download the latest version from Internet and put (MD5.class) beside your codes (in WEB-INF) and then whenever you need to Encrypt sth, simply write

MD5.getHashString(WHAT_TO_BE_ENCRYPTED)

.

The code works, but I can’t read the String to encrypt sent by a form.
I want to make a servlet that reads the strings sent by a form, encrypt them, and put them in a cookie.
I tried to use the

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
String Password = request.getParameter("pass");
}

to read the strings sent by the form, but it gives me problems with the main.
I don’t know how to solve this problem :slight_smile:

Hi,

It’s because you have named the input field “Pass” and requesting parameter “pass”. As far as I remember the parameters are case-sensitive.

Best regards,

Yes, they are case-sensitive but my last post was only an example.
I better write again the code


import java.io.UnsupportedEncodingException;
import javax.crypto.*;
import javax.swing.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class EncryptDecrypt {
Cipher ecipher;
Cipher dcipher;
 
EncryptDecrypt(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
 
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
 
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
 
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
 
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
 
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
 
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
 
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
 
 
 
 
public static void main(String[] args){
try{
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
 
// Create encrypter/decrypter class
EncryptDecrypt encrypter = new EncryptDecrypt(key);
 
// Get the pass from the form
String Password = request.getParameter("pass");
 
// Encrypt
String encrypted = encrypter.encrypt(Password);
 
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
 
// Output
 
System.out.println("Encrypted: "+encrypted);
System.out.println("Decrypted: "+decrypted);
 
} catch (Exception e) {
}
}
}

Now I don’t know where do I have to put this
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException [COLOR=#66CC66]{

}[/COLOR]

to make the request.getParameter(“pass”) work, or whatever do I have to do :frowning:

Well, if you just want to use the JSP, you don’t have to use servlet.
Just copy the logic in main to your JSP page.

If you want to use servlet, you need to go though the servlet tutorials because you sound like you haven’t use it before.

Yes, I want to do this with a servlet.
I worked with servlets before but I never used one in which there are some methods and then a main. I always used the
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
}
as “main”.
So, now, I don’t know what to do.
If you can tell me how to do or post some link to make me understand how to do I’ll be very grateful :slight_smile:

Ah ok. If you know how to get the form information to the doPost method, then just copy the code you have in main into your doPost method.

Thank you very much, now the compiler gives me no error :slight_smile:
But :stuck_out_tongue: when I try to use it as a servlet I don’t know what happens…I put EncryptDecrypt.java in the src folder, than EncryptDecrypt.class in the classes folder and then set the web.xml with the new servlet.
I wrote an html form to try the servlet and I got this error:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Error instantiating servlet class EncryptDecrypt
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
java.lang.Thread.run(Unknown Source)

root cause

java.lang.InstantiationException: EncryptDecrypt
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
java.lang.Thread.run(Unknown Source)

note The full stack trace of the root cause is available in the Apache Tomcat/6.0.13 logs.
Apache Tomcat/6.0.13

I write here the file source:

EncryptDecrypt.java

import java.io.UnsupportedEncodingException;
import javax.crypto.*;
import javax.swing.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EncryptDecrypt {
Cipher ecipher;
Cipher dcipher;

EncryptDecrypt(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);

} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}

public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");

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

// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}

public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

// Decrypt
byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}




public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try{
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();

// Create encrypter/decrypter class
EncryptDecrypt encrypter = new EncryptDecrypt(key);

//Pass variable I should get from the form with the request.getParameter("Pass");
String Password = request.getParameter("pass");

// Encrypt
String encrypted = encrypter.encrypt(Password);

// Decrypt
String decrypted = encrypter.decrypt(encrypted);

// Output

System.out.println("<html><head><title>Cripta Decripta</title></head><body>");
System.out.println("Encrypted: "+encrypted+"<br/>");
System.out.println("Decrypted: "+decrypted+"<br/><br/>");
System.out.println("<a href='formencrypt.html'>Form</a></body></html>");

} catch (Exception e) {
}
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">

    <servlet>
       <servlet-name>EncryptDecrypt</servlet-name>
       <servlet-class>EncryptDecrypt</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>EncryptDecrypt</servlet-name>
        <url-pattern>/EncryptDecrypt</url-pattern>
    </servlet-mapping>

</web-app>

formencrypt.html

<html>
<head>
<title>Form Encrypt</title>
</head>
<body>
<form method="post" action="EncryptDecrypt">

Password <input type="password" name="pass"/><br/>
<input type="submit" value="Entra">
</form>
</body>
</html>

I really don’t know from what this error is caused :frowning:

Almost, your servlet need to expend the HttpServlet class, try:

public class EncryptDecrypt extends HttpServlet

And recompile.

You’re so right :smiley: I forgot it :stuck_out_tongue: Thanks :slight_smile:

Now I did it, compile is ok, same error by Tomcat :frowning:

Oh, try adding a default constructor to your class:

EncryptDecrypt() {}