I have two simple methods that encrypt and decrypt Strings. Now the ENCRYPT seems to be wokring OK, but the DECRYPT is giving me the following error...
Now I have this working ages ago and have only just gone back to it because I need it for an App I'm working on, I think the problem is to do with the retrieved String that is going into the Decrypter.
Here is the code for the two methods...
This is the problem. Encrypted data is binary - it can't be converted to a String this easily. If you need a string representation of encrypted data, use something like base-64 encoding. The Apache Commons Codec library has an implementation of that.
SecretKey implements Serializable, so you can store it any way you want.
Or, for a cross-language compatible way, SecretKey.getEncoded() gets you the byte that makes up the key. If you store that somewhere, you can recreate the key later using "new SecretKeySpec(byte, String)".
Just so I understand, if I was to generate a SecretKey and store it to a file so that my Decrypt class could read it later... If I was to then run the Encrypt code agai, would it not over-write the old Secretkey and therefore make any data encrypted by the first Encrypt 'lost', as it's SecretKey would now be gone?
Keith Seller wrote:Just so I understand, if I was to generate a SecretKey and store it to a file so that my Decrypt class could read it later... If I was to then run the Encrypt code agai, would it not over-write the old Secretkey and therefore make any data encrypted by the first Encrypt 'lost', as it's SecretKey would now be gone?
Well. thats up to you.... As written, you generate a new key with every encrypt, so you will need to store it in a way that the decrypt can find the matching key. Personally, I would recommend have the key generation, and storage completely separated -- and have both the encrypt and decrypt get the key from this location.
I basically have a seperate method that creates a file on the server called secretkey.dat which contains the generatedKey.
Now each time the doEncryption() and doDecryption() methods run, they check to see if this file exists. If it does they read the key from the file for the encryption, that way all my encrypted adat is using the same key and therefore decryption works!
no wonder he is so sad, he hasn't seen this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss