(String masterPassword, String password)
| 105 | } |
| 106 | |
| 107 | private String encrypt(String masterPassword, String password) { |
| 108 | try { |
| 109 | byte[] salt = generateSalt(); |
| 110 | SecretKey key = deriveKey(masterPassword.toCharArray(), salt); |
| 111 | Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); |
| 112 | byte[] iv = new byte[IV_LENGTH]; |
| 113 | new SecureRandom().nextBytes(iv); |
| 114 | IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); |
| 115 | cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec); |
| 116 | byte[] encrypted = cipher.doFinal(password.getBytes()); |
| 117 | byte[] combined = new byte[salt.length + iv.length + encrypted.length]; |
| 118 | System.arraycopy(salt, 0, combined, 0, salt.length); |
| 119 | System.arraycopy(iv, 0, combined, salt.length, iv.length); |
| 120 | System.arraycopy(encrypted, 0, combined, salt.length + iv.length, encrypted.length); |
| 121 | String encryptedPassword = Base64.getEncoder().encodeToString(combined); |
| 122 | |
| 123 | // Write encrypted password to file |
| 124 | writeToFile(encryptedPassword); |
| 125 | |
| 126 | return encryptedPassword; |
| 127 | } catch (Exception e) { |
| 128 | JOptionPane.showMessageDialog(this, "Encryption failed: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); |
| 129 | return null; |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | private void writeToFile(String encryptedPassword) { |
| 134 | try (BufferedWriter writer = new BufferedWriter(new FileWriter(ENCRYPTED_PASSWORD_FILE))) { |
no test coverage detected