|
35 | 35 | public class ExampleStringEncryptionPasswordBasedInOneMethod { |
36 | 36 | private static final Logger LOGGER = Logger.getLogger(ExampleStringEncryptionPasswordBasedInOneMethod.class.getName()); |
37 | 37 |
|
38 | | - public static void main(String[] args) { |
39 | | - String plainText = "Text that is going to be sent over an insecure channel and must be encrypted at all costs!"; |
| 38 | + /** |
| 39 | + * Demonstrational method that encrypts the plainText using a password (that is used to derive the required key). |
| 40 | + * @param plainText |
| 41 | + * @param password |
| 42 | + * @return true if encryption and decryption is working, false otherwise |
| 43 | + */ |
| 44 | + public static boolean demonstratePasswordBasedSymmetricEncryption(String plainText, String password) { |
40 | 45 | try { |
41 | | - String password = null; |
42 | 46 | // GENERATE password (not needed if you have a password already) |
43 | 47 | if(password == null || password.isEmpty()) { |
44 | 48 | KeyGenerator keyGen = KeyGenerator.getInstance("AES"); |
@@ -76,9 +80,15 @@ public static void main(String[] args) { |
76 | 80 | String decryptedCipherText = new String(decryptedCipherTextBytes, StandardCharsets.UTF_8); |
77 | 81 |
|
78 | 82 | LOGGER.log(Level.INFO, () -> String.format("Decrypted and original plain text are the same: %b", decryptedCipherText.compareTo(plainText) == 0)); |
| 83 | + return decryptedCipherText.compareTo(plainText) == 0; |
79 | 84 | } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterException | InvalidAlgorithmParameterException | InvalidKeySpecException e) { |
80 | 85 | LOGGER.log(Level.SEVERE, e.getLocalizedMessage()); |
| 86 | + return false; |
81 | 87 | } |
82 | 88 | } |
83 | 89 |
|
| 90 | + public static void main(String[] args) { |
| 91 | + demonstratePasswordBasedSymmetricEncryption("Text that is going to be sent over an insecure channel and must be encrypted at all costs!",null); |
| 92 | + } |
| 93 | + |
84 | 94 | } |
0 commit comments