Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java passphrase encryption

I'm trying to learn how to do passphrase-based encryption with Java. I'm finding several examples online, but none (yet) on Stack Overflow. The examples are a little light on explanation for me, particularly regarding algorithm selection. There seems to be a lot of passing strings around to say what algorithms to use, but little documentation as to where the strings came from and what they mean. And it also seems like the different algorithms may require different implementations of the KeySpec class, so I'm not sure what algorithms can use the PBEKeySpec class I'm looking at. Furthermore, the examples all seem a little out of date, many requiring you to get an older cryptography package that used to not be part of the JDK, or even a third-party implementation.

Can someone provide a straightforward introduction to what I need to do to implement encrypt(String data, String passphrase) and decrypt(byte[] data, String passphrase)?

like image 950
skiphoppy Avatar asked Dec 16 '08 18:12

skiphoppy


People also ask

What is passphrase in encryption?

A passphrase is similar to a password. However, a password generally refers to something used to authenticate or log into a system. A passphrase generally refers to a secret used to protect an encryption key. Commonly, an actual encryption key is derived from the passphrase and used to encrypt the protected resource.

Does Java support AES 256?

Java and AES encryption inputs.In Java, we can use SecureRandom to generate the random IV. 1.2 The AES secret key, either AES-128 or AES-256 .


1 Answers

I'll be cautious about giving or taking security-related advice from a forum... the specifics are quite intricate, and often become outdated quickly.

Having said that, I think Sun's Java Cryptography Architecture (JCA) Reference Guide is a good starting point. Check out the accompanying code example illustrating Password-Based Encryption (PBE).

Btw, the standard JRE provides only a few options out-of-the-box for PBE ("PBEWithMD5AndDES" is one of them). For more choices, you'll need the "strong encryption pack" or some third-party provider like Bouncy Castle. Another alternative would be to implement your own PBE using the hash and cipher algorithms provided in the JRE. You can implement PBE with SHA-256 and AES-128 this way (sample encrypt/decrypt methods).

Briefly, the encrypt method for PBE may involve the following steps:

  1. Get password and cleartext from the user, and convert them to byte arrays.
  2. Generate a secure random salt.
  3. Append the salt to the password and compute its cryptographic hash. Repeat this many times.
  4. Encrypt the cleartext using the resulting hash as the initialization vector and/or secret key.
  5. Save the salt and the resulting ciphertext.
like image 122
Zach Scrivena Avatar answered Sep 22 '22 19:09

Zach Scrivena