0

I read: Java 256-bit AES Password-Based Encryption and several other entries here.

I also had a look at this: http://pastebin.com/YiwbCAW8

What am I doing: I want to protect a file (users.dat) with AES, I simply use a chain of output and input streams.

object -> cipher -> buffered -> fileoutputstream

fileinputstream -> buffered -> cipher -> object

So when I restart the application,I want to load the data stored in that file (users.dat).

I always get this exception when reading the file (users.dat). Prior reading from users.dat, i read the secret bytes from key.dat

java.io.StreamCorruptedException: invalid stream header: 7E000274
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at edu.hm.wedoit.usermanagement.impl.UserManagementImpl.loadUsers(UserManagementImpl.java:256)
at edu.hm.wedoit.usermanagement.impl.UserManagementImpl.<init>(UserManagementImpl.java:105)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:125)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:270)
//.... more spring 

First If there is no key file, I create the secret key and write it to a file (key.dat) locally (not encrypted):

        try(BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(keyFile)))
    {
byte[] secretBytes = secret.getEncoded();
bos.write(secretBytes)
}
//catch

-32115-4061-70-102115-33-123-6494159-6-86115 (output from simple for loop, these are the bytes wrote to file)

Code for Keycreation:

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec("wedoit".toCharArray(), SALT, 65536, 128); 
//note I only use 128 here because 256 doesnt work despite having local_policy.jar / US_export_policy.jar in {jdk}/lib/security 

        SecretKey tmp = factory.generateSecret(spec);
        secretBytes = tmp.getEncoded();
        secret = new SecretKeySpec(secretBytes, "AES");
        saveSecret(secret); //saves the bytes to a simple file via object / ciper / buffered / fileoutputstream 

Secdond On Startup if the keyfile exists, i read the bytes from the file.

-32115-4061-70-102115-33-123-6494159-6-86115 (same as the output from above)

    try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(keyFile)))
    {
        byte[] secretBytes = new byte[16];
bis.read(secretBytes);
return secretBytes;
}
//catch

For me it seems the writing/reading into the keyfile seems to work

secretBytes = loadKey(); 
secret = new SecretKeySpec(secretBytes, "AES"); // I thought the key will be reconstructed here?

So here is some more code I am using for cipher initialization.

        encryptionCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] ivbyte = encryptionCipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();

    encryptionCipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivbyte));

    decryptionCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    decryptionCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivbyte));

Update I use try-with-resource (Input / Output).

        try(ObjectInputStream ois = new ObjectInputStream(
            new CipherInputStream(new BufferedInputStream(new FileInputStream(userdbFile)),decryptionCipher)))
    {

        // .... ois.readObject();....
    }
//...catch...

What am I doing wrong?

edit updated a little to clarify the situation, about the files i am talking. Thanks so far for your comments!


Already clarified: (moved here)

I noticed something strange, but I dont know if it is important (successive calls, with different output):

EDIT: Seems not to be imported, thanks to jon in the comments

System.out.println(secret.getEncoded()); // [B@5c7e77fe
System.out.println(secret.getEncoded()); // [B@78b23edb
System.out.println(secret.getEncoded()); // [B@1e64a539
Community
  • 1
  • 1
Bernhard
  • 13
  • 5
  • `getEncoded()` returns a `byte[]` - and calling `toString()` on that doesn't show the data, because arrays don't override `toString()`. You probably want to convert the content to hex or base64. – Jon Skeet Nov 01 '15 at 12:27
  • 2
    I fail to understand the question. You start by saying that reading the key throws an exception (without posting the stack trace), then you continue by saying that loading the key returns the same bytes as the ones saved. Post a *complete, minimal* program reproducing the problem. And if you have an exception, post its stack trace. – JB Nizet Nov 01 '15 at 12:33
  • Possible duplicate of [Java: Syntax and meaning behind "\[B@1ef9157"? Binary/Address?](http://stackoverflow.com/questions/1040868/java-syntax-and-meaning-behind-b1ef9157-binary-address) – Artjom B. Nov 01 '15 at 12:35
  • thanks for your answers, the issue is not that the sysout prints these Codes. I understand now why they are different. But thats not the issue. – Bernhard Nov 01 '15 at 15:17

0 Answers0