Java Generate Aes Key Random
String encryption in Java with key generation. Random key generation using strong secure random number generator. AES-256 authenticated. // GENERATE random. To generate secrete key we can use Java KeyGenerator class which provides the functionality of a secret (symmetric) key generator. Key generators are constructed using one of the getInstance class methods of this class. What is the recommended way of generating a secure, random AES key in Java, using the standard JDK? In other posts, I have found this, but using a SecretKeyFactory might be a better idea: KeyGene.
So to explain what i need to do in this programme, is to create an AES key and a private and public key using RSA algorithm. I then wanna encrypt a msg with the AES key and then encrypt that AES key with the RSA public key. And in the end decrypt the message with the RSA private key.
I have only managed to encrypt the message with AES , i have also encrypted the AES key with RSA public key but i cant seem to get the decrytion to work, in other words to decrypt that message with the private key. Im not sure how to move forward, im totally stuck.
Any advice? here is the code. Im very new to cryptography
AESKeyGeneration.java generates the sysmetric key using AES algorithm. Key size assigned here is 128 bits. It works for key size of 192 and 256 bits also by adding secuirty related files to jre1.6.0 lib security folder. RandomKeygen is a free mobile-friendly tool that offers randomly generated keys and passwords you can use to secure any application, service or device. KEY RandomKeygen - The Secure Password & Keygen Generator. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec around it. But there are still advantages to the method you are using: the KeyGenerator is specifically created to generate keys. /wifi-password-key-generator-online.html. This means that the code may be optimized for this generation.
Help us help you and TellTheDetails.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
fred rosenberger wrote:How do you know it doesn't work? What I mean is, do you get a compiler error? a run time error? Does it throw an exception? Does it run to completion, but the data it decrypted doesn't match what was encrypted?
Help us help you and TellTheDetails.
Oh im sorry, i wasnt clear. Well i get the pop up asi want from JOptionPane message dialog the message encrypted but not decrypted. So what i see is a message saying :: text encrpyted : fuhgudhgug and text decrypted : fhdhgidg
(as an example) . So it doesnt decrypt it with the private key i suspect.
fred rosenberger wrote:How do you know it doesn't work? What I mean is, do you get a compiler error? a run time error? Does it throw an exception? Does it run to completion, but the data it decrypted doesn't match what was encrypted?
Help us help you and TellTheDetails.
No errors, beautifully smoothly compiling just not decrypting it at all and it has to be decrypted with the RSA private key so im very stuck on what im doing wrong :/
Also breaking up the excessively long line).
Campbell Ritchie wrote:Too difficult for this forum: moving.
Also breaking up the excessively long line).
Sorry, didnt know
Stephan van Hulst wrote:You're encrypting your message using a symmetric key, and then you're never using that encrypted data again. You're only decrypting your symmetric key. You still need to decrypt your message using your decrypted key.
so im only decrypting the AES key not the message and RSA key itself? thanks, need to take a look at it.
Stephan van Hulst wrote:Keep in mind that both AES and RSA may use block ciphers that use an initialization vector, so when you initialize a cipher for decryption, you may need to pass it the IV used by the encrypting cipher.
If RSA is being used to encrypt the AES key then it should use something like PKCS1 padding since that padding introduces a random element. AES used with ECB padding is susceptible to ciphertext forgery and in order to avoid this AES should always be used with one of the feedback modes such as CBC and use a random IV. The random IV does not need to be kept secret and can be passed in the clear along with the AES ciphertext. One approach is to pre-pend the IV to the AES ciphertext. Using this approach one would ship the RSA encrypted AES key followed by the IV followed by the AES cyphertext.
Richard Tookey wrote:
Stephan van Hulst wrote:Keep in mind that both AES and RSA may use block ciphers that use an initialization vector, so when you initialize a cipher for decryption, you may need to pass it the IV used by the encrypting cipher.
If RSA is being used to encrypt the AES key then it should use something like PKCS1 padding since that padding introduces a random element. AES used with ECB padding is susceptible to ciphertext forgery and in order to avoid this AES should always be used with one of the feedback modes such as CBC and use a random IV. The random IV does not need to be kept secret and can be passed in the clear along with the AES ciphertext. One approach is to pre-pend the IV to the AES ciphertext. Using this approach one would ship the RSA encrypted AES key followed by the IV followed by the AES cyphertext.
Thanks for advice you guys.. my issue is atm that i do not know where in my code to re-use the encrypted data in order to decrypt it. I just feel lost and confused. I have used the PKCS1 padding thanks to your advice and im not getting that kind of error any longer. I thought padding error had to do with the fact that i was trying to convert byte to string but maybe thats not correct? In any case right now im trying to figure out how to re-use my encrypted string 'InputText1'. Im starting to think that maybe it is complicated to decrypt a string that is not a pre-defined specific word or sentence like lets say 'Hello world', or does it matter? It worked to encrypt so should work to decrypt as well. Sorry ive been working with this for a while and i just feel dizzy lately :P
Preliminary -
Create the RSA public and private keys. The public key will be used in the encryption section and the private key used in the decryption.
Encryption section -
1) Create a random AES key.
2) Encrypt this AES key with the RSA public key. Write the encrypted key it to the output.
3) Create a random IV for use with AES encryption.
4) Write it to the output.
5) Encrypt your cleartext with AES using the random AES key and random IV. Write the result to the output.
Decryption section -
1) Read the encrypted AES key from the input.
2) Decrypt the encrypted AES key using the RSA private key.
3) Read the IV from the input.
4) Using the exracted AES key and extracted IV decrypt the rest of the input. This is the recovered cleartext.
Note 1 - DataOutputStream and DataInputStream are very useful in reading and writing since they allow you to write a set of bytes as a length followed by the bytes.
Note 2 - Since this is an exercise you can chain the DataOutputStream to a ByteArrayOutptuStream if you don't actually want to save the output to a file. You can then use the content of the ByteArrayInput to a ByteArrayInputStream chained to a DataInputStream for use in decryption.
Note 3 - You can get away with using ECB mode in the AES cipher as long as you use a random AES key. You would then ignore the IV requirement.
Richard Tookey wrote:It is not obvious from your code what you are trying to do except that it must be an assignment since in general one needs two programs; one to encrypt the cleartext to create the ciphertext and the other to decrypt the ciphertext to recover the cleartext. As an exercise one can just use one program but use two sections; one to encrypt and one to decrypt.
Preliminary -
Create the RSA public and private keys. The public key will be used in the encryption section and the private key used in the decryption.
Encryption section -
1) Create a random AES key.
2) Encrypt this AES key with the RSA public key. Write the encrypted key it to the output.
3) Create a random IV for use with AES encryption.
4) Write it to the output.
5) Encrypt your cleartext with AES using the random AES key and random IV. Write the result to the output.
Decryption section -
1) Read the encrypted AES key from the input.
2) Decrypt the encrypted AES key using the RSA private key.
3) Read the IV from the input.
4) Using the exracted AES key and extracted IV decrypt the rest of the input. This is the recovered cleartext.
Note 1 - DataOutputStream and DataInputStream are very useful in reading and writing since they allow you to write a set of bytes as a length followed by the bytes.
Note 2 - Since this is an exercise you can chain the DataOutputStream to a ByteArrayOutptuStream if you don't actually want to save the output to a file. You can then use the content of the ByteArrayInput to a ByteArrayInputStream chained to a DataInputStream for use in decryption.
Note 3 - You can get away with using ECB mode in the AES cipher as long as you use a random AES key. You would then ignore the IV requirement.
Yes thank you. Its an assignment but we were supposed to create two programmes but it was ok dto do just one if we managed to solve it that way but come to think of it i think its better to do two. Thank you for your help. Ive been thinking about outputstream encrypting a file and send it that way but didnt thinnk it was necessary in just one programme but maybe its better. Thanks for your advice and help.
Richard Tookey wrote:3) Create a random IV for use with AES encryption.
It's not necessary to do this explicitly. Cipher will generate an IV automatically for algorithms that require one. Just call getIV() on the cipher, and send that.
Stephan van Hulst wrote:
Richard Tookey wrote:3) Create a random IV for use with AES encryption.
It's not necessary to do this explicitly. Cipher will generate an IV automatically for algorithms that require one. Just call getIV() on the cipher, and send that.
True. I'm just showing how stale I am.
Howdy.
I am having the same issue when doing the Encryp/decrypt with aes/rsa mechanism.
can you please share your sample code of doing it.
thanks in advance.
- marc
“There’s as many atoms in a single molecule of your DNA as there are stars in the typical galaxy. We are, each of us, a little universe.” ― Neil deGrasse Tyson, Cosmos
Contents
- Conclusion
1. Introduction
The Advanced Encryption Standard (AES) is a standard for encryption and decryption that has been approved by the U.S. NIST (National Institute of Standards and Technology) in 2001. It is more secure than the previous encryption standard DES(Data Encryption Standard) and 3DES(Triple-DES). You should be using AES for all symmetric encryption needs in preference to DES and 3DES (which are now deprecated).
Symmetric Encryption refers to algorithms that use the same key for encryption as well as decryption. As such, the key should be kept secret and must be exchanged between the encryptor and decryptor using a secure channel.
The core java libraries provide good support for all aspects of encryption and decryption using AES so no external libraries are required. In this article, we show you how to properly perform encryption and decryption using AES with just the core java API.
[Note: Check out how to use AES for file encryption and decryption in python.]
2. The Imports
We need the following import statements for the program.
3. Generate an Initialization Vector (IV)
When using AES with a mode known as CBC (Cipher Block Chaining), you need to generate an initialization vector (IV). In the CBC mode, each plaintext block is XORed with the previous ciphertext block before being encrypted. So you need an initialization vector for the first block. To produce different ciphertext with each run of the encryption (even with the same plaintext and key), we use a random initialization vector.
Java Generate Aes Key Random Number
To generate the IV, we use the SecureRandomclass. The block size required depends on the AES encryption block size. For the default block size of 128 bits, we need an initialization vector of 16 bytes.
Java Generate Aes Key Random Number
From the initialization vector, we create an IvParameterSpecwhich is required when creating the Cipher.
You can save the initialization vector for transmission along with the ciphertext as follows. This file can be transmitted plainly i.e. no encryption is required.
4. Generating or Loading a Secret Key
If you do not already have a key, you should generate one as follows:
If you have a key (maybe one generated previously and stored securely), you can load it from a binary key file using the following code:
If you need to save a generated key for future usage (maybe for loading using the above code), you can do it as follows:
5. Creating the Cipher
The Cipher object is the one that handles the actual encryption and decryption. It needs the secret key and the IvParameterSpec created above.
When encrypting, create the Cipher object as follows:
For decryption, you need to load the initialization vector and create the IvParameterSpec.
Now you can create the Cipher object:
6. Encrypting a String
Once the Cipher object is created, you can perform the encryption. The encryption process works with byte arrays.
To encrypt a String, first convert it to a byte array by encoding it in UTF-8. Then write the data to a file as follows:
7. Decrypting Back to a String
Read back encrypted text and convert it to a String as follows:
8. Encrypting a File
The procedure for encrypting a file is a bit more involved. Read the input data in a loop and invoke Cipher.update(). If a byte array is returned, you can write it to the output file. Finally wrap up with a Cipher.doFinal().
Invoke the encryption as follows:
9. Decrypting a File
The outfile obtained from the above procedure can be decrypted quite simply by specifying the decrypt mode as follows:
And that covers the whole story of encryption and decryption using AES.
Conclusion
The process for encrypting and decrypting using AES is a bit involved. First you generate an IV (initialization vector) and then generate (or load) a secret key. Next you create a cipher object which you can use for encryption and decryption.