How to insert an encrypted field into a table in PostgreSQL?

3

I wanted to know how to insert an encrypted field into a table in the database. To illustrate my question let's suppose I have the following java class:

package pessoa;

public class Pessoa {

    private String email;
    private String senha ;
    private String nomecompleto ;   
    ..
    ..
    ..

}

You will have the following entity in the database:

CREATE TABLE usuario
    (
      email character varying(50) NOT NULL,
      senha character varying(200) NOT NULL,
      nomecompleto character varying(100) NOT NULL,
     PRIMARY KEY (email)
    )

The question is: How can I encrypt the field in the java application or in the database? And how can I do this? Do I have to create a method to encrypt in the java code or is something already ready to use?

    
asked by anonymous 25.09.2015 / 23:07

1 answer

4

Answers to individual questions:

  • I encrypted the field in the java application or in the database?
  • The best option is to encrypt the application side as soon as you receive the information to be encrypted.

  • And how can I do this?
  • It's not that simple, but there are a number of things that are ready for known, safe, and recommended algorithms on the internet, and adapt them to your specific use case.

    For example, you could use PBKDF2 to store passwords. See an example using Java common libraries: link

  • Do I have to create a method to encrypt in the java code or is there something ready to use already?
  • See 2. =]

    Security

    Encryption of passwords should not be reversible. The answer link quoted in the question comments should not be considered for password encryption, as it is reversible, and even has security issues with some of the answers.

    It is recommended that a strong password "encryption" algorithm be used, such as bcrypt or pbkdf2 . Java has implementations for these algorithms, so you just have to adapt your table (in usuario ) to store the additional values that the chosen algorithm needs.

    Modern computers have in-processor instructions that make it much faster to execute hash functions like SHA and MD5; in addition, the GPU allows multiple hashes to be generated simultaneously, increasing a lot the amount of tests per second in a brute force attack. These algorithms are made to be not only mathematically secure but slow to run especially on a GPU, which has the advantage of parallelism.

    In any case, if you want to use something really simple, use something like the following:

  • Add a salt column to your usuario table.

  • Choose a known non-collapsed hash, such as SHA2 or SHA3 (and use the 256-bit version or higher).

  • In the password column, store (in pseudo-code):

    usuario.senha = hash(concatena(salt, senha_digitada));

  • To validate the password, use the expression (in pseudo-code):
  • senha_valida = usuario.senha == hash(concatena(salt, senha_digitada));

        
    26.09.2015 / 05:45