Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Bouncy Castle AES encryption \ decryption

843810Aug 12 2004 — edited Aug 13 2004
Hi,
can someone please take a look and advice why the following code does not work?
I am trying to encrypt a message using bouncy castle AES and then decrypt it, but I don't get the original message back after decryption.

my code:

import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.params.KeyParameter;

public class AesCipher
{

public static void main(String[] args)
{
byte[] key = StringByteArrayConverter.convertStringToHexByteArray("3c028e5e78f5f9217d214e004d291797");
KeyParameter keyParameter = new KeyParameter(key);
String messageToEncode = "1234567891234567";

String encodedMessage = encode(keyParameter, messageToEncode);
String decodedMessage = decode(keyParameter, encodedMessage);
}

private static String encode(KeyParameter keyParameter, String messageToEncode)
{
System.out.println("Original message: " + messageToEncode);
byte[] messageToEncodeBytes = messageToEncode.getBytes();
byte[] encodedMessageBytes = new byte[128];
AESEngine encoder = new AESEngine();
encoder.init(true, keyParameter);
int totalBytesEncoded = encoder.processBlock(messageToEncodeBytes, 0, encodedMessageBytes, 0);
String encodedMessage = new String(encodedMessageBytes, 0, totalBytesEncoded);
System.out.println("Encoded message: " + encodedMessage);
return encodedMessage;
}

private static String decode(KeyParameter keyParameter, String messageToDecode)
{
AESEngine decoder = new AESEngine();
decoder.init(false, keyParameter);
byte[] messageToDecodeBytes = messageToDecode.getBytes();
byte[] decodedMessageBytes = new byte[128];
int totalBytesDecoded = decoder.processBlock(messageToDecodeBytes, 0, decodedMessageBytes, 0);
String decodedMessage = new String(decodedMessageBytes, 0, totalBytesDecoded);
System.out.println("Decoded message: " + decodedMessage);
return decodedMessage;
}
}

two notes:
1. I assume there is not a problem with the key parameter as both the encoder and the decoder accept it.
2. I am intentionally working with a 16 length string - equals to the cipher block size.

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 10 2004
Added on Aug 12 2004
3 comments
854 views