There is a little bit of confusion in your code, maybe because some method you called are missing, or maybe because you are using your keys to encrypt...your keys(!!!)
Let's try to encrypt and decrypt the easy way, removing all the stuff that is not strictly needed in your code (like encode your key and save it to a file, and then restore the key without decoding it, etc..).
Let's take a look at the following simplified code based on your:
KeyGenerator keyGenS = KeyGenerator.getInstance("AES");
keyGenS.init(128);
SecretKey sKey1 = keyGenS.generateKey();
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE,sKey1);
byte[] byteText = "Insert here whatever you want to crypt".getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteText);
We have generated our key with KeyGenerator, and then we have initialized our Cipher instance with that key. At this point we simply call doFinal()
passing the plainText we want to encrypt.
That's all for the encryption part. Of course you can save your keys and byteCipherText
to a file if you want, but all the other staff is (at least) useless.
The decryption part is easy as the encryption. The logic is the same.
If you saved your key on a file, just read it into a byte[]
, and use it for initialize your cipher instance. Something like this:
aesCipher.init(Cipher.DECRYPT_MODE, sKey1);
byte[] plainText = aesCipher.doFinal(byteCipherText);
If you put all the above code into a main()
and run it, you should have into plainText
the same text as in byteText
.
You can verify it with a
System.out.println(new String(plainText));
Try to start from here, then add all other things you may need.
Hope this helps.
Regards