Reputation: 1272
Hi i have explore many good site about AES Encryption, Most Site will be nicely detail about how to encrypt files and really help me understand the AES Encryption.
but i am still unclear about how to produce files that is encrypted. this tutorial example explain how AES encryption was done but i still cannot see the physical encrypted file. Most example show only how to encrypt and decrypt but did not explain about how to produce encrypted physical file.
My Question here is how do we actually produce an actual encrypted files, i believe this question is relevance to SO citizen as this might help other in future.
Answer The code below will encrypt a text file with physical encrypted file.
final Path origFile = Paths.get("C:\\3.txt");
final byte[] contents = Files.readAllBytes(origFile);
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(contents.toString().getBytes());
System.out.println("encrypted string: " + encrypted.toString());
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original =cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " +originalString);
final Path newFile = Paths.get("C:\\3encrypted.aes");
Files.write(newFile, encrypted, StandardOpenOption.CREATE);
}
As fge suggest, this is not suite for encrypting large file. ill provide new answer when i done with my research.
Upvotes: 0
Views: 214
Reputation: 121710
Your code is not correct; you try and read bytes from a file and then put it into a StringBuffer
which is a character sequence. Don't do that!
Read the bytes directly:
final Path origFile = Paths.get("C:\\3.txt");
final byte[] contents = Files.readAllBytes(origFile);
Then encrypt like you do, and write your encrypted
byte array into a new file:
final Path newFile = Paths.get("C:\\3encrypted.aes"); // or another name
Files.write(newFile, encrypted, StandardOpenOption.CREATE);
It is very important to understand that String
is not suitable for binary data. Please see this link for more details.
Upvotes: 2