Hi everyone, i am trying to use some java code to encrypt passwords entering a database on the system i am building, please could someone explain what the code below is doing and if it would be useful for encrypting passwords. Thanks

import java.util.StringTokenizer;
 
public class Encryption {
 
 
    public static String encrypt(String password) {
        StringBuffer sb = new StringBuffer();
 
        for (int i = 0; i<password.length(); i++) {
 
            char c = password.charAt(i);
            int j = c;
            sb.append(String.valueOf(j) + " ");
        }
        return sb.toString().trim();
    }
 
 
    public static String decrypt(String encryptedPassword) {
        StringTokenizer st = new StringTokenizer(encryptedPassword, " ");
        //A StringTokenizer takes a string as input and breaks it upto tokens, seperated by " "
        StringBuffer sb = new StringBuffer();
        while (st.hasMoreTokens()) {
            int c = Integer.parseInt(st.nextToken());
            char chr = (char) c;
            sb.append(chr);
        }
        return sb.toString();
    }
}

I don't see where you're encrypting it... You get the char value from the int value, which is from the same char value, so you're really doing nothing there. You need to get the ascii value and add least add something to it.

Member Avatar for iamthwee

if it would be useful for encrypting passwords?

What, for real databases? Probably not, the encryption system looks weak.

Isn't there some java API for this anyway?

I don't see where you're encrypting it... You get the char value from the int value, which is from the same char value, so you're really doing nothing there. You need to get the ascii value and add least add something to it.

Do you know any kind of java class i can use to encrypt passwords goin into a Mysql database.:sad:

There's always MD5, if you never have to recover the readable password again.

Java has a crypto and security package. It will do everything for you, but probably the same amount of time will be taken because you'll need to learn it.

I wouldn't recommend using java to do any encryption to the database. DBs have their own encryption built in. Just add the DBs encryption on your jdbc call.


UPDATE users SET password = AES_ENCRYPT(`users password`, `your encryption key` WHERE id=`101`;

This makes it so you don't have to have encryption in each and every java application that touches the database. Much nicer in my opinion.


The above example is for a mysql database.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.