This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Java in General and the fly likes Java and PHP Encryption Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Java and PHP Encryption" Watch "Java and PHP Encryption" New topic
Author

Java and PHP Encryption

Michael Anderson
Greenhorn

Joined: Oct 19, 2007
Posts: 4
I'm using an open source web application (Moodle), which is mostly using PHP. My Java question; What is the best method to encrypt passwords using Java, that will also be compatible with PHP?

IOW: password = EncryptData(password);
Marcus Green
arch rival
Rancher

Joined: Sep 14, 1999
Posts: 2813
Moodle stores passwords in a hashed format, i.e. so you can compare passwords but not decrypt them. If you want to modify Moodle you are probably better off doing it in PHP as then it fits in nicely with everything else. PHP is quite easy to learn and use, and there's no shame in using it it if you (like me) are a serious Java type person.

(Last year I went to visit the creator of Moodle Martin Dougiamas in Perth Western Australia, he is a very, very cool guy).


SCWCD: Online Course, 50,000+ words and 200+ questions
http://www.examulator.com/moodle/course/view.php?id=5&topic=all
Michael Anderson
Greenhorn

Joined: Oct 19, 2007
Posts: 4
My java program is reading data from a M$ SQL data. This contains user info that is being inserted into the Moodle users table, and contains their passwd in clear text. I need to insert it encrypted. Here is the code: /* its ok to criticize the code, even welcome, */

/* Program Name: Moodletest:
Description: Move Zangle data into Moodle Database.
Author: Michael Anderson
Date: 10/18/2007
==============================================================================
Author: Michael Anderson (Writing COBOL for 1/4 century)
*/
import javax.sql.*;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.lang.*;
import java.text.*;
import java.util.Date;
public class Moodletest {
public static java.sql.Connection zcon = null;
public static java.sql.Connection mcon = null;
public static String url = null;
public static String serverName = null;
public static String portNumber = null;
public static String databaseName = null;
public static String userName = null;
public static String password = null;
public static String selectMethod = null;

public Moodletest() {
String zquery = "select distinct * from Moodle_Users where username > ''";
Statement zstmt;
StringBuffer mquery = new StringBuffer(" ");

try
{
zstmt = zcon.createStatement();

ResultSet zrs = zstmt.executeQuery(zquery);
ResultSetMetaData zrsmd = zrs.getMetaData();

//PrintColumnTypes.printColTypes(zrsmd);
System.out.println("");

int numberOfColumns = zrsmd.getColumnCount();

for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(", ");
String columnName = zrsmd.getColumnName(i);
System.out.print(columnName);
}
System.out.println("");

while (zrs.next()) {
int id = zrs.getInt(1);
String auth = zrs.getString(2);
int confirmed = zrs.getInt(3);
int policyagreed = zrs.getInt(4);
int deleted = zrs.getInt(5);
int mnethostid = zrs.getInt(6);
String username = zrs.getString(7);
String passwd = zrs.getString(8);
String idnumber = zrs.getString(9);
String lastname = zrs.getString(10);
String firstname = zrs.getString(11);
String email = zrs.getString(12);
int emailstop = zrs.getInt(13);
String icq = zrs.getString(14);
String skype = zrs.getString(15);
String yahoo = zrs.getString(16);
String aim = zrs.getString(17);
String msn = zrs.getString(18);
String phone1 = zrs.getString(19);
String phone2 = zrs.getString(20);
String institution = zrs.getString(21);
String department = zrs.getString(22);
String address = zrs.getString(23);
String city = zrs.getString(24);
String country = zrs.getString(25);
String lang = zrs.getString(26);
String theme = zrs.getString(27);
int timezone = zrs.getInt(28);
int firstaccess = zrs.getInt(29);
int lastaccess = zrs.getInt(30);
int lastlogin = zrs.getInt(31);
int currentlogin = zrs.getInt(32);
String lastip = zrs.getString(33);
String secret = zrs.getString(34);
int picture = zrs.getInt(35);
String url = zrs.getString(36);
String description = zrs.getString(37);
int mailformat = zrs.getInt(38);
int maildigest = zrs.getInt(39);
int maildisplay = zrs.getInt(40);
int htmleditor = zrs.getInt(41);
int ajax = zrs.getInt(42);
int autosubscribe = zrs.getInt(43);
int trackforums = zrs.getInt(44);
int timemodified = zrs.getInt(45);
int trustbitmask = zrs.getInt(46);
String imagealt = zrs.getString(47);
int screenreader = zrs.getInt(48);
mquery = new StringBuffer(" ");
java.sql.Statement mdlstatement = null;
mdlstatement = mcon.createStatement();
mquery.append("INSERT INTO moodle18.mdl_user");
mquery.append("(auth, confirmed, policyagreed, deleted, mnethostid, username, password, idnumber, firstname, lastname, email, emailstop, icq, skype, yahoo, aim, msn, phone1, phone2, institution, department, address, city, country, lang, theme, timezone, firstaccess, lastaccess, lastlogin, currentlogin, lastip, secret, picture, url, description, mailformat, maildigest, maildisplay, htmleditor, ajax, autosubscribe, trackforums, timemodified, trustbitmask, imagealt, screenreader) ");
mquery.append("VALUES ('");
mquery.append(auth);
mquery.append("',");
mquery.append(confirmed);
mquery.append(",");
mquery.append(policyagreed);
mquery.append(",");
mquery.append(deleted);
mquery.append(",");
mquery.append(mnethostid);
mquery.append(",'");
mquery.append(username);
mquery.append("','");
mquery.append(passwd);
mquery.append("','");
mquery.append(idnumber);
mquery.append("','");
mquery.append(lastname);
mquery.append("','");
mquery.append(firstname);
mquery.append("','");
mquery.append(email);
mquery.append("',");
mquery.append(emailstop);
mquery.append(",'");
mquery.append(icq);
mquery.append("','");
mquery.append(skype);
mquery.append("','");
mquery.append(yahoo);
mquery.append("','");
mquery.append(aim);
mquery.append("','");
mquery.append(msn);
mquery.append("','");
mquery.append(phone1);
mquery.append("','");
mquery.append(phone2);
mquery.append("','");
mquery.append(institution);
mquery.append("','");
mquery.append(department);
mquery.append("','");
mquery.append(address);
mquery.append("','");
mquery.append(city);
mquery.append("','");
mquery.append(country);
mquery.append("','");
mquery.append(lang);
mquery.append("','");
mquery.append(theme);
mquery.append("',");
mquery.append(timezone);
mquery.append(",");
mquery.append(firstaccess);
mquery.append(",");
mquery.append(lastaccess);
mquery.append(",");
mquery.append(lastlogin);
mquery.append(",");
mquery.append(currentlogin);
mquery.append(",'");
mquery.append(lastip);
mquery.append("','");
mquery.append(secret);
mquery.append("',");
mquery.append(picture);
mquery.append(",'");
mquery.append(url);
mquery.append("','");
mquery.append(description);
mquery.append("',");
mquery.append(mailformat);
mquery.append(",");
mquery.append(maildigest);
mquery.append(",");
mquery.append(maildisplay);
mquery.append(",");
mquery.append(htmleditor);
mquery.append(",");
mquery.append(ajax);
mquery.append(",");
mquery.append(autosubscribe);
mquery.append(",");
mquery.append(trackforums);
mquery.append(",");
mquery.append(timemodified);
mquery.append(",");
mquery.append(trustbitmask);
mquery.append(",'");
mquery.append(imagealt);
mquery.append("',");
mquery.append(screenreader);
mquery.append(");");
try {
mdlstatement.executeUpdate(mquery.toString());
mquery = new StringBuffer(" ");
}
catch (SQLException sqlExa)
{
System.out.println(mquery.toString());
sqlExa.printStackTrace();
// Write some data to the stream

Date now = new Date();
System.out.println(now.toString());
System.out.println(sqlExa.toString());
System.out.println(mquery.toString());
System.out.println(" \n");
// System.exit(0);
}

System.out.println("");

}
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}

//
public static String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
//
public static void main(String[] args) {
Date now = new Date();
System.out.println(" ");
System.out.println("Java " + System.getProperty("java.version")
+ " " + System.getProperty("os.arch") + " platform, "
+ " running " + System.getProperty("os.name"));
String message = now.toString();
url = "jdbc:microsoft:sqlserver://";
serverName = "zangsql";
portNumber = "1433";
databaseName = "zanglesisd";
userName = "xx";
password = "xxxxxx";
selectMethod = "cursor";
message += ":";
message += "Connecting to Zangle Database ";
System.out.println(message);
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
zcon = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(zcon!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
System.out.println("MSSQL Conn = " + zcon);
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{ if(zcon!=null){
dm = zcon.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
if (dm.supportsBatchUpdates()) {
System.out.println(" Batching is supported");
} else {
System.out.println(" Batching is not supported");
}
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
message += ":";
message += "Connecting to Moodle Database ";
System.out.println(message);
System.out.println(" ");

String url = "jdbc:mysql://10.10.0.55/";
String serverName = "10.10.0.55";
String portNumber = "3306";
String databaseName = "moodle18";
String userName = "xx";
String password = "xxxxxx";
String selectMethod = "cursor";

try{
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
mcon = DriverManager.getConnection (url, userName, password);
if(mcon!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
System.out.println("Mysql Conn = " + mcon);
dm = null;
rs = null;

dm=null;
new Moodletest();
try{
if(mcon!=null) mcon.close();
mcon=null;
} catch(Exception ee){ ee.printStackTrace();}
try{
if(zcon!=null) zcon.close();
zcon=null;
} catch(Exception ee){ ee.printStackTrace();}
}
}
Yohan Liyanage
Ranch Hand

Joined: Aug 17, 2007
Posts: 132

If you are OK to use hashing, you could make use of a hashing algorithm like SHA1 or MD5. Both are supported by Java, PHP and even MySQL.
Only problem is, these algorithms are one-way hashing algorithms. You cannot retrieve the password back from it. One thing you can do is compare the hashes, instead of passwords.

For Java, you could make use of java.security.MessageDigest class. It supports both algorithms.

And for PHP, you could make use of the functions sha1() and md5().

MySQL also has built-in functions which can be used to generate hashes. They are SHA1(), SHA() and MD5().

If its really necessary for you to retrieve the password, you may consider using an encoding algorithm like Base64. PHP natively supports it through base64_encode() and base64_decode(). For Java, you will have to use a freely available Base64 Implementation(Just Google for it).
[ October 20, 2007: Message edited by: Yohan Liyanage ]

Yohan Liyanage
http://blog.yohanliyanage.com
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

If its really necessary for you to retrieve the password, you may consider using an encoding algorithm like Base64. PHP natively supports it through base64_encode() and base64_decode(). For Java, you will have to use a freely available Base64 Implementation(Just Google for it).


Actually no. Base64 is *not* an encyption algorithm. You might as well use a rot13 on the password, it probably just as easy to break...

If you want to encrypt the password, and later be able to retrieve the password, you need to actually encrypt it. Take a look at the javax.crypto.Cipher class -- which supports a large set of encryption and decryption algorithms.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

Originally posted by Henry Wong:

If you want to encrypt the password, and later be able to retrieve the password, you need to actually encrypt it. Take a look at the javax.crypto.Cipher class -- which supports a large set of encryption and decryption algorithms.


I have never, in over 30 years of programming, needed to retrieve the password. Just tell the user "you can't retrieve it, but will gladly reset it to xyzzy". Then use a HMAC

If you do try to use any of the real ciphers (I'd use AES) then you have a significant problem with how to you protect the key used for the cipher.
If you hard code it into your Java source, then anyone with access to the source has the key. If you keep it in a file/property on the disk, anyone with access to the disk has access to the key.

Its a non-trivial problem, and all solutions have serious security or sysadmin risks.

Which is why I always use a HMAC
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

I have never, in over 30 years of programming, needed to retrieve the password. Just tell the user "you can't retrieve it, but will gladly reset it to xyzzy". Then use a HMAC


Unfortunately, in my case, I can't say never. I would say that I have encountered the need, in about a handful of times.

While it sounds good to never have to retrieve the password, you don't get to code the password server all the time -- sometimes your program is a client to another system. Nor can you expect your users to have a single sign on facility. If you have to hold passwords on behalf of your users, so that you can access external services -- your program will be challenged for the password, not for a hash.

And what if you have to store passwords which you use? For example, the admin password to the client database? Your program can't depend on the DBA, everytime that it is restarted -- nor would he/she appreciate your program storing it in the clear.

Henry
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

If you hard code it into your Java source, then anyone with access to the source has the key. If you keep it in a file/property on the disk, anyone with access to the disk has access to the key.

Its a non-trivial problem, and all solutions have serious security or sysadmin risks.



I think of it like this. The goal is not to find a solution that is 100 percent perfect. The goal is to find a solution that is more secure than everything around it.

For example, if the local datastore (on the client) is not secure, then don't have the client challenge for the password -- have all the password challenges on the server, and have the client use a token (from the server), once it users passes the challenge. This way, the server can store it in the local datastore, which can be more secure.

Of course, someone with the admin password on the server now has access to the user passwords. But quite frankly, if someone that you don't trust has admin access to your server, you have way more problems than one program/service.


A good analogy to this is... If you encounter a hungry bear in the forest, you don't have to outrun the bear. You just have to outrun the person next to you...

Henry
[ October 20, 2007: Message edited by: Henry Wong ]
Yohan Liyanage
Ranch Hand

Joined: Aug 17, 2007
Posts: 132

Actually no. Base64 is *not* an encyption algorithm.


Yes Henry. I agree with you. Base64 is NOT an encryption algorithm. Thats why I said :

you may consider using an encoding algorithm like Base64.



 
GeeCON Prague 2014
 
subject: Java and PHP Encryption