diff --git a/java_landing_page.md b/java_landing_page.md index df75b30..4feb5da 100644 --- a/java_landing_page.md +++ b/java_landing_page.md @@ -12,7 +12,7 @@ is_landingpage: 1 | | All in One | Easy Object oriented | |-------------------------------------------------|----------------------------------------|--------------------------------------| | Symmetric Encryption | [String Encryption (password based) ✔](java_string_encryption_password_based_symmetric.html)
[String Encryption (key based) ✔](java_string_encryption_key_based_symmetric.html)
[File Encryption ✔](java_file_encryption_symmetric_password_based.html) | [String Encryption with separate class ✔](java_easy_AES_string_encryption.html)
[File Encryption with separate class ✔](java_easy_AES_file_encryption.html) | -| Asymmetric Encryption / Public Key Cryptography | | | +| Asymmetric Encryption / Public Key Cryptography | [String Encryption ✔](java_asymmetric_string_encryption.html) | | | Key Storage | | | | Hashing | [String Hash ✔](java_string_hash.html) | N/A | | Crypto Provider Setup | | | diff --git a/java_string_encryption_asymmetric.md b/java_string_encryption_asymmetric.md new file mode 100644 index 0000000..e677ad9 --- /dev/null +++ b/java_string_encryption_asymmetric.md @@ -0,0 +1,41 @@ +--- +title: Asymmetric String Encryption using Java JDK +keywords: sample +summary: "Asymmetric String Encryption in Java" +permalink: java_asymmetric_string_encryption.html +folder: Java JDK +references: [ + # Place a list of references used to create and/or understand this example. + { + url: "https://docs.oracle.com/javase/10/docs/api/javax/crypto/Cipher.html", + description: "Java JDK Ciper" + } +] +authors: [ + { + name: "Kai Mindermann", + url: "https://github.com/kmindi" + } +] +# List all reviewers that reviewed this version of the example. When the example is updated all old reviews +# must be removed from the list below and the code has to be reviewed again. The complete review process +# is documented in the main repository of CryptoExamples +current_reviews: [ + +] +# Indicates when this example was last updated/created. Reviews don't change this. +last_updated: "2018-04-28" +tags: [Java, RSA, Asymmetric, String, Encryption] +--- + +## Use cases + +- + +## Sample Code for Java based asymmetric encryption + +```java +{% include_relative src/main/java/com/cryptoexamples/java/ExampleAsymmetricStringEncryptionInOneMethod.java %} +``` + +{% include links.html %} diff --git a/src/main/java/com/cryptoexamples/java/ExampleAsymmetricStringEncryptionInOneMethod.java b/src/main/java/com/cryptoexamples/java/ExampleAsymmetricStringEncryptionInOneMethod.java new file mode 100644 index 0000000..3f8b85a --- /dev/null +++ b/src/main/java/com/cryptoexamples/java/ExampleAsymmetricStringEncryptionInOneMethod.java @@ -0,0 +1,56 @@ +package com.cryptoexamples.java; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * All in one example for asymmetric encryption and decryption of a string in one method. + * - Generation of public and private RSA 4096 bit keypair + * - AES-256 authenticated encryption using GCM + * - BASE64-encoding as representation for the byte-arrays + * - UTF-8 encoding of String + * - Exception handling + */ +public class ExampleAsymmetricStringEncryptionInOneMethod { + private static final Logger LOGGER = Logger.getLogger(ExampleAsymmetricStringEncryptionInOneMethod.class.getName()); + + public static void main(String[] args) { + String plainText = "Text that is going to be sent over an insecure channel and must be encrypted at all costs!"; + try { + + // GENERATE NEW KEYPAIR + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + /* @see https://www.keylength.com/ */ + keyPairGenerator.initialize(4096); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + + // ENCRYPTION + Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); + cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); + + byte[] byteCipher = cipher.doFinal(plainText.getBytes()); + + // CONVERSION of raw bytes to BASE64 representation + String cipherText = new String(Base64.getEncoder().encode(byteCipher)); + + // DECRYPTION + cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); + byte[] decryptedCipher = cipher.doFinal(Base64.getDecoder().decode(cipherText)); + String decryptedCipherText = new String(decryptedCipher); + + LOGGER.log(Level.INFO, () -> String.format("Decrypted and original plain text are the same: %b", decryptedCipherText.compareTo(plainText) == 0)); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterException e) { + LOGGER.log(Level.SEVERE, e.getMessage(), e); + } + } +} diff --git a/src/test/java/com/cryptoexamples/java/EncryptionInOneMethodTests.java b/src/test/java/com/cryptoexamples/java/EncryptionInOneMethodTests.java index ffc715e..14ffd92 100644 --- a/src/test/java/com/cryptoexamples/java/EncryptionInOneMethodTests.java +++ b/src/test/java/com/cryptoexamples/java/EncryptionInOneMethodTests.java @@ -46,6 +46,12 @@ public void testStringEncryptionKeyBasedMain() { assertThat(errContent.toString(), containsString("Decrypted and original plain text are the same: true")); } + @Test + public void testAsymmetricStringEncryptionMain() { + ExampleAsymmetricStringEncryptionInOneMethod.main(new String[1]); + assertThat(errContent.toString(), containsString("Decrypted and original plain text are the same: true")); + } + @Test public void testFileEncryptionMain() { ExampleFileEncryptionInOneMethod.main(new String[1]);