package main;
import java.io.*;
import java.util.Arrays;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class Test {
public void encryptKey(SecretKey customerKey, String userPassword) {
try {
byte[] passwordHash = MessageDigest.getInstance("SHA-256").digest(userPassword.getBytes()); //Benutzer-Passwort mittel SHA-256 hashen
byte[] hash128 = Arrays.copyOf(passwordHash, 16); //Davon die ersten 128 Bit (16 x 8 Bit) verwenden
SecretKey tempKey = new SecretKeySpec(hash128, "AES"); //AES-Schlüssel mit dem Benutzer-Passwort erstellen
Cipher cip = Cipher.getInstance("AES");
cip.init(Cipher.ENCRYPT_MODE, tempKey);
CipherOutputStream cipOut = new CipherOutputStream(new FileOutputStream("C:\\NameOfKey.key"), cip);
cipOut.write(customerKey.getEncoded());
cipOut.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public SecretKey decryptKey(String userPassword) {
try {
byte[] passwordHash = MessageDigest.getInstance("SHA-256").digest(userPassword.getBytes());
byte[] hash128 = Arrays.copyOf(passwordHash, 16);
SecretKey tempKey = new SecretKeySpec(hash128, "AES");
Cipher cip = Cipher.getInstance("AES");
cip.init(Cipher.DECRYPT_MODE, tempKey);
CipherInputStream cipIn = new CipherInputStream(new FileInputStream("C:\\NameOfKey.key"), cip);
byte[] readKey = cipIn.readAllBytes();
return new SecretKeySpec(readKey, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}