1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
public class AESEncryption {
private byte[] randomSalt = null;
private char[] password = null;
AlgorithmParameters params = null;
private SecretKey aesKey = null;
public AESEncryption()
{
}
private byte[] generateSecureRandomSalt()
{
try {
SecureRandom mySecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[1024];
mySecureRandom.nextBytes(bytes);
return bytes;
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public void encrypt (char[] password, File file)
{
this.password = password;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, generateRandomKey());
params = cipher.getParameters();
FileInputStream fis = new FileInputStream(file);
byte[] fileContent = new byte[(int)file.length()];
fis.read(fileContent);
CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(file.getName()), cipher);
cos.write(cipher.doFinal(fileContent));
cos.close();
// END OF encrypting the file
} catch (NoSuchAlgorithmException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (NoSuchPaddingException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (InvalidKeyException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (InvalidParameterSpecException e) {
System.out.println("[ERROR] " + e.getMessage());
/*} catch (IllegalBlockSizeException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (BadPaddingException e) {
System.out.println("[ERROR] " + e.getMessage());*/
} catch (UnsupportedEncodingException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (FileNotFoundException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (IOException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (IllegalBlockSizeException e) {
System.out.println("[ERROR] " + e.getMessage());
} catch (BadPaddingException e) {
System.out.println("[ERROR] " + e.getMessage());
}
}
private SecretKey generateRandomKey()
{
try {
/* Derive the key, given password and salt. */
randomSalt = generateSecureRandomSalt();
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, randomSalt, 20000, 128);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
aesKey = secret;
return secret;
} catch (NoSuchAlgorithmException e) {
System.out.println("[ERROR] " + e.getMessage());
}
catch (InvalidKeySpecException e)
{
System.out.println("[ERROR] " + e.getMessage());
}
catch (NullPointerException e)
{
System.out.println("[ERROR] " + e.getMessage());
}
return null;
}
} |
Partager