Encryption with Java and PostgreSQL / MYSQL

5

Hello I have a question in my college project, in scope it says like this:  "Users and passwords can be stored in the database, using the bank's own encryption."

Is the crypto in both default by MD5? In that case I need to use the MD5 crypto both in my java application and in the bank or just in the bank is it possible? Thanks!

    
asked by anonymous 28.07.2015 / 19:16

2 answers

2

In Postgre you can encrypt a string manually with the bank's own functions.

For example, the MD5 (varchar) function:

INSERT INTO usuario (id, nome, senha) VALUES (1, 'Joao',md5('123'));

By doing a SELECT we can get:

1   "Joao"   "202cb962ac59075b964b07152d234b70"
    
29.07.2015 / 00:02
2

To encrypt a password or any other string you do it in the application or in the bank. Here I will deal with SHA1 and MD5 , however the latter is no longer recommended, see How to safely have hash passwords? .

PostgresSQL

MD5

SELECT md5(senha);

SHA1

The MD5 algorithm is now ready to be used in your bank, but the SHA1 is not. To be used the pg_crypto extension must be created with your selected schema and then you can use the digest function which also has other algorithms besides SHA1.

CREATE EXTENSION pgcrypto;
SELECT encode(digest('senha', 'sha1'), 'hex');

MySQL

MD5

SELECT md5('senha');

SHA1

SELECT sha1('senha');

Java

// MD5
String criptografadaMd5 = criptografar("123456", "MD5");
// SHA1
String criptografadaSha1 = criptografar("123456", "SHA1");

public static String cripografar(String input, String tipoAlgoritmo) throws NoSuchAlgorithmException {
    MessageDigest mDigest = MessageDigest.getInstance(tipoAlgoritmo);
    byte[] result = mDigest.digest(input.getBytes());
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < result.length; i++) {
        sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
    }

    return sb.toString();
}
    
29.07.2015 / 14:45