Advertisement
Guest User

keystore

a guest
Oct 13th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. package sample.logic;
  2.  
  3. import javax.crypto.KeyGenerator;
  4. import javax.crypto.SecretKey;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.security.KeyStore;
  9. import java.security.KeyStoreException;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.security.UnrecoverableKeyException;
  12. import java.security.cert.CertificateException;
  13.  
  14. class KeyLoader {
  15.  
  16. private static final String KEYSTORE_TYPE = "JCEKS";
  17. private static final String KEYSTORE_NAME = "KeyStore";
  18. private static final String SECRET_KEY_NAME = "secretKeyAlias";
  19. private static final String KEYSTORE_PWD = "password";
  20.  
  21. static SecretKey getKey(String algorithm) throws SecretKeyException{
  22.  
  23. SecretKey key = loadKey();
  24.  
  25. if (key == null){
  26. try {
  27. key = KeyGenerator.getInstance(algorithm).generateKey();
  28. } catch (NoSuchAlgorithmException e) {
  29. throw new SecretKeyException();
  30. }
  31. try {
  32. storeKey(key);
  33. } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
  34. throw new SecretKeyException();
  35. }
  36. }
  37.  
  38. return key;
  39. }
  40.  
  41. private static void storeKey(SecretKey secretKey) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
  42.  
  43. KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
  44. ks.load(null, KEYSTORE_PWD.toCharArray());
  45.  
  46. KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray());
  47. KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(secretKey);
  48. ks.setEntry(SECRET_KEY_NAME, skEntry, protParam);
  49. try (FileOutputStream fos = new FileOutputStream(KEYSTORE_NAME)) {
  50. ks.store(fos, KEYSTORE_PWD.toCharArray());
  51. } catch (Exception asd) {
  52. System.out.println(asd.getMessage());
  53. }
  54. }
  55.  
  56. private static SecretKey loadKey() {
  57. KeyStore ks = null;
  58. try {
  59. ks = KeyStore.getInstance(KEYSTORE_TYPE);
  60. ks.load(new FileInputStream(KEYSTORE_NAME), KEYSTORE_PWD.toCharArray());
  61. }
  62.  
  63. catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
  64. System.out.println(e.getMessage());
  65. return null;
  66. }
  67. try {
  68. return (SecretKey) ks.getKey(SECRET_KEY_NAME, KEYSTORE_PWD.toCharArray());
  69. } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
  70. System.out.println(e.getMessage());
  71. return null;
  72. }
  73. }
  74.  
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement