Reputation: 85
I'm creating a network system, everything works fine, except encryption. I'm using CipherOutputStream and CipherInputStream. So I've started debugging... so I created a separate application that generates AES encryption key and uses it in Cipher. The code:
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
CipherOutputStream cipherOutputStream = new CipherOutputStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
System.out.println("Test");
System.out.print(((char) b));
}
}, cipher);
cipherOutputStream.write('c');
Nothing get's printed into the console. Does anyone know where is the problem?
Upvotes: 1
Views: 410
Reputation: 93968
You are using ECB mode, which is the default for the standard / open JDK. So "AES"
gets translated to "AES/ECB/PKCS5Padding"
. Now ECB requires full blocks as input during encryption / decryption. Only the last part of the message may not be a complete block: it gets padded before encryption using PKCS#7 standard (PKCS#5 is the same thing).
Great, so what happens is that you write a single byte. This byte is obviously not a complete block. So the cipherstream is going to wait for more bytes to come in to form a complete block. If it gets closed or it will pad the remaining bytes and put them to the connected output stream. As long as you don't close the stream however, nothing gets written.
I'd use try-with-resources
to get around this issue. And please use at least an inner class or something like that instead of defining it on the same line.
Upvotes: 2