For encryption I use something like this:
SecretKey aesKey = KeyGenerator.getInstance("AES").generateKey();
StringEncrypter aesEncrypt = new StringEncrypter(aesKey, aesKey.getAlgorithm());
String aesEncrypted= aesEncrypt.encrypt(StringContent);
If I print out aesKey I get: "javax.crypto.spec.SecretKeySpec@1708d".
So for encryption I would like to ask user for key but dont know how and what format should it be. My plan was something like this:
SecretKey aesKey = javax.crypto.spec.SecretKeySpec@1708d;
StringEncrypter aesEncrypt = new StringEncrypter(aesKey, aesKey.getAlgorithm());
String aesDecrypt = aesEncrypt.decrypt(aesEncrypted);
But seems its not working. Is there some easy way to print out the key after encryption to console so user can save it(or remember it) and then Use for Decryption ?
Whole code is here:Cannot decrypt cyphertext from text file, symmetric key implement. in java So Im sorry for posting again but Im not sure If the code is even readable(I'm newbie).
The Advanced Encryption Standard (AES, Rijndael) is a block cipher encryption and decryption algorithm, the most used encryption algorithm in the worldwide. The AES processes block of 128 bits using a secret key of 128, 192, or 256 bits.
I've had to do this myself recently. And while the other answers here led me in the right direction, it could have been easier. So here is my "share" for the day, a couple of helper methods for simple AES key manipulation. (Note the dependency on Apache Commons and Codec.)
This is all in a git repo now: github.com/stuinzuri/SimpleJavaKeyStore
import static org.apache.commons.codec.binary.Hex.*;
import static org.apache.commons.io.FileUtils.*;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import org.apache.commons.codec.DecoderException;
public static SecretKey generateKey() throws NoSuchAlgorithmException
{
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256); // 128 default; 192 and 256 also possible
return keyGenerator.generateKey();
}
public static void saveKey(SecretKey key, File file) throws IOException
{
char[] hex = encodeHex(key.getEncoded());
writeStringToFile(file, String.valueOf(hex));
}
public static SecretKey loadKey(File file) throws IOException
{
String data = new String(readFileToByteArray(file));
byte[] encoded;
try {
encoded = decodeHex(data.toCharArray());
} catch (DecoderException e) {
e.printStackTrace();
return null;
}
return new SecretKeySpec(encoded, "AES");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With