Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java AES Encryption with salt

Alright, turns out I suck at Encryption/Decryption. I just dont get it. How can I make Java encrypt String message1 = "hello world"; with String salt = "mySalt"; using AES encryption? also how can I decrypt it once encrypted?

If you have the time to provide the most basic code, it would help me a lot.

Also 1 general question about AES encryption, using the same salt, will the same message always have the same encryption?

Thanks in advance.

like image 777
cody Avatar asked Sep 05 '11 01:09

cody


2 Answers

AES doesn't have a concept of a salt. It just takes data, and a key. For the same input, it will always generate the same output.

How you combine your message with your salt is up to you. String concatenation is probably sufficient. But note that salts don't really make a lot of sense for something like AES, because it's not a hash algorithm.

like image 156
Oliver Charlesworth Avatar answered Sep 18 '22 21:09

Oliver Charlesworth


With Spring Security Crypto, it is simplified (mainly because they default to the password based encryption rather than other forms):

final String password = "A private password that you need to keep secret.";  
final String salt = KeyGenerators.string().generateKey();
TextEncryptor encryptor = Encryptors.text(password, salt);

String cipherText = encryptor.encrypt(textToEncrypt);

String decryptedText = encryptor.decrypt(cipherText);

AES is just a cipher, and you can use an IV with the text you are encrypting. With symmetric encryption, the salt is used for the key/secret that you encrypt with, as you can see above.

In the real world you will have to deal with distributed systems, shared keys and salts across the cluster, etc, etc. Lots of fun.

Spring Security is a thin abstraction over JCE, so it's easy to adapt if you don't use Spring itself.

like image 20
JeeBee Avatar answered Sep 17 '22 21:09

JeeBee