i want to store encrypted password in my mysql database.
i have insert the password like ari means have to save the password like B-dd2c1cd0250859d32754fdd85ffc0531.
But i have to insert the data(ari) means the ari is displayed on my database.how can i encrupt the password and save the password like above format.
For eg:
ari is save in database like these format B-dd2c1cd0250859d32754fdd85ffc0531.how can i do.please help me.
i have wrote the code:
public class Insert {
public String insertData(String userName,String userPassword){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://server:3306/android","XXXX","XXX");
PreparedStatement statement = con.prepareStatement("INSERT INTO xcart_customers(login,password) VALUES ('"+userName+"','"+userPassword+"');");
int result = statement.executeUpdate();
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return "Insertion successfull!!";
}}
This is my Demo.java class:
public class Demo {
public static void main(String[] args){
Insert obj = new Insert();
System.out.println(obj.insertData("krishna", "ari"));
}
}
Looking at the sql query INSERT INTO xcart_customers(login,password) I guess you are trying to encrypt passwords for X-CART.
X-CART uses Blowfish key-based encryption. You can find your key from config.php -file.
Here's a already answered question about encrypting blowfish with a key in java which might help figuring out how encrypt it
Encryption with BlowFish in Java
You need to look at password hashing and salting. Have a look at this post.
EDIT:
Remember Hashing is One way! so you can't expect to convert the Hashed value back to the clear text (in this case ari). What you can do is when login works you can check user entered value is equal or not to the database value.
Without knowing which scheme was used to encrypt the existing data, there's no way to tell how you can achieve compatibility. If you can start all over again, bcrypt is the way to go.
Related
I use MD5 algorithm to hash passwords with salt. After registering a user, I store both hashed password and salt in my SQL database. Unfortunately, when I retrieve them, later, so as to compare them with the user's input I address a problem with the encoding of salt. I store salt as VARCHAR(16) and when I try to retrieve it from my DataBase, it converts in a different form. This is my code :
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
String DB_salt1 = rs.getString("Salt");
byte [] DB_salt = DB_salt1.getBytes();
I used some System.out.println(); functions in order to locate the problem and I found out that byte [] DB_salt = DB_salt1.getBytes(); outputs the wrong salt, while String DB_salt1 = rs.getString("Salt"); outputs the proper one. My guess is that it happens byte loss.
EDIT: To clarify, the proper salt and the one stored in my DataBase, let's say is [B#4e25154. String DB_salt1 = rs.getString("Salt"); stores this salt; the proper one. But when byte [] DB_salt = DB_salt1.getBytes(); is executed, it outputs a different salt, which ruins the whole process.
The best way to store the passwords in the Database is using Bcrypt. With this you don't need to store the salt.
Below is the sample code that uses Bcrypt.
1) String pw_hash = BCrypt.hashpw("PLAIN PASSWORD", BCrypt.gensalt());
2) Store the pw_hash in DB
3) if(BCrypt.checkpw("PLAIN PASSWORD", pw_hash)){ System.out.println("Success Login"); }else{ System.out.println("Failure Login"); }
Steps 1 and 2 will be followed while user registering the password for the first time. While Step 3 is used if the given password is matching with the encrypted password.
how can I simulate this code in mysql:
Encrypt
TextEncryptor encryptor = Encryptors.text(key, salt);
encryptor.encrypt(message);
Decrypt
TextEncryptor decryptor = Encryptors.text(key, salt);
decryptor.decrypt(message);
I need decrypt the data from the db that I encrytp in java code.
Use AES_ENCRYPT / AES_DECRYPT
INSERT INTO t VALUES (1, AES_ENCRYPT('text',UNHEX('F3229A0B371ED2D9441B830D21A390C3')));
https://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_aes-encrypt
Mysql offers a range of encryption functions, out of which only aes_encrypt() has not been deprecated yet.
However, if you want to encrypt data stored in databases, you may consider applying encryption on an operating system or database product level, so your data is encrypted, but you can still use sql to filter your data without much inconvenience.
I'm rewriting old java desktop swing app to JSF application using PrimeFaces.
The old app didn't use hibernate but I have decided to use it in new app. Everything works fine but the problem is when I want to save passwords with hibernate using MySql’s function password().
Is there a way to do this because it would be nice if I could import data from old database to new database without changing passwords.
I managed to bring login to work using this code snippet:
public User login(String username, String password) {
User result = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
String sql = "select s from User where username=:username and password=password(:password)";
Query query = session.createQuery(sql);
query.setString("username", username);
query.setString("password", password);
result = (User) query.uniqueResult();
if (result != null) {
Hibernate.initialize(result.getUserData());
}
}
finally {
session.close();
}
return result;
}
But here is problem with registration of new users since I don't know how store passwords. The code I’m using to save users to database looks like:
public User addUser(User obj) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.save(obj);
session.flush();
}
finally {
session.close();
}
return obj;
}
I know I could write the whole insert statement the old fashioned way but what’s the point of using hibernate then and the code would look ugly. Also I’m not happy with login snippet as well.
I’ve also tried to update password with trigger after insert but I kept getting error:
Updating of NEW row is not allowed in after trigger
So I abandoned this approach since its ugly and it doesn’t work.
Should I just use jasypt or any other library to encrypt password in applications and be done with it? Or is there an elegant solution to my problem.
The MySql function password() should not be used at all for hashing passwords! From the documentation:
The PASSWORD() function is used by the authentication system in MySQL
Server; you should not use it in your own applications.
The calculation is fast and unsalted, which makes it very unsecure. Instead leave the hashing to the server side language and use a library which uses a slow hash function with a cost factor like BCrypt, PBKDF2 or SCrypt. A wellknown library for Java is jBCrypt.
Using Jasypt EncryptedStringType is much more convenient, since you delegate the password hashing to the UserType.
This way your application logic doesn't have to deal with password related responsibilities (like it's the case of your SELECT using the non-portable PASSWORD SQL function).
The UserType will also take care of hashing the actual password for an INSERT/UPDATE too.
So, Jasypt is a much better alternative.
I am trying to build a simple login form using Swing in Java. I created a Sample form with two fields.
usernamefield of type TextField
passfield of type PasswordField
Now I have a database and in that a login table which has following structure.
username | password
----------------------
abcd | xyz
Also I created a connection to database. and I am able to access table data by using ResultSet.
I made an object of database connection called conn.
I know that password is stored in the form of char array.
so when I try to match password by using following code it does not work.
if(usernamefield.getText() == conn.username && passfield.getPassword().toString == conn.password) {
system.out.println("Correct");
}else {
system.out.println("Incorrect");
}
Above code always go to else block.
I also noticed that passfield.getPassword() prints the correct password while passfield.getPassword().toString prints some random characters like [C#76dab03c
How to resolve it?
Use equals instead of == and it should work. Never use == on strings, it hardly ever produces the result you expect.
I think the more serious issue with your code is that you're storing passwords in plain text. That is a huge security risk. You should look into password hashing algorithms, for instance bcrypt.
You must compare string with .equals(), not ==, but you're doing this wrong anyway. The password should be hashed at the database, and you should be passing what the user entered to the database and having it do the matching, via a WHERE clause using the appropriate hash function. In other words, ask the database to fetch the user row with this username and password.
I am attempting to use the Shiro JdbcRealm and SHA256 hashedcredentialsMatcher. I need to update a legacy database and assign the appropriate salt for each user (via a batch routine).
how do I get/set the salt for a given account using the Shiro framework?
With Shiro 1.2.3 all you need to do is:
Extend JdbcRealm and set salt style.
public class JdbcSaltRealm extends JdbcRealm {
public JdbcSaltRealm() {
setSaltStyle(SaltStyle.COLUMN);
}
}
Update shiro.ini to use extended realm and to get salt column from DB
credentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName = SHA-256
jdbcRealm = com.mypackage.JdbcSaltRealm
jdbcRealm.authenticationQuery = SELECT password, salt FROM user WHERE username = ?
jdbcRealm.credentialsMatcher = $credentialsMatcher
Hash & salt current / new user passwords. This should be done for all existing users as well as on new user registrations.
private void saltHashPassword(String password) {
String salt = new BigInteger(250, new SecureRandom()).toString(32);
//TODO: save salt value to "salt" column in user table
Sha256Hash hash = new Sha256Hash(password,
(new SimpleByteSource(salt)).getBytes());
String saltedHashedPassword = hash.toHex();
//TODO: save saltedHashedPassword value to "password" column in user table
}
I hope my answer is clear and understandable.
Maybe a bit late:
Have a look at this tutorial.
Meri, the guy who owns the blog, describes exactly how to create an own salted JDBC Realm.
This is also an acknowledged improvement in the community for version 1.3.0 .
Hope this helpes, have Fun!