From 6ac5fd3e048a69fd6af6022a0ef416f8b379c85a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Flesch=20Tam=C3=A1s?= Date: Thu, 2 May 2024 11:09:06 +0200 Subject: [PATCH] encrypt and decrypt a message with the java cipher class --- .../hu/saborsoft/blockchain/TestChipher1.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/hu/saborsoft/blockchain/TestChipher1.java diff --git a/src/main/java/hu/saborsoft/blockchain/TestChipher1.java b/src/main/java/hu/saborsoft/blockchain/TestChipher1.java new file mode 100644 index 0000000..8174f1b --- /dev/null +++ b/src/main/java/hu/saborsoft/blockchain/TestChipher1.java @@ -0,0 +1,46 @@ +package hu.saborsoft.blockchain; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import java.security.SecureRandom; + +public class TestChipher1 { + + public static final String MESSAGE = "If you were a drop of tear in my eyes"; + + private static final Logger LOG = LoggerFactory.getLogger(TestChipher1.class); + + public static void main(String[] args) throws Exception { + LOG.debug("Original message: {}", MESSAGE); + SecretKey key = createSecretKey(); + + // encrypt the original message + Cipher encrypter = initCipher(Cipher.ENCRYPT_MODE, key); + byte[] cipherText = encrypter.doFinal(MESSAGE.getBytes()); + LOG.debug("Encrypted text: {}", new String(cipherText)); + + // it is not mandatory, we can modify the type of the first cipher object but in the real world + // this would be the case, a new cipher object for decryption + Cipher decrypter = initCipher(Cipher.DECRYPT_MODE, key); + byte[] decoded = decrypter.doFinal(cipherText); + LOG.debug("Decoded string: {}", new String(decoded)); + } + + private static SecretKey createSecretKey() throws Exception { + KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); + SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); + keyGenerator.init(sr); + return keyGenerator.generateKey(); + } + + private static Cipher initCipher(int cipherMode, SecretKey key) throws Exception { + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(cipherMode, key); + return cipher; + } + +}