You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by se...@apache.org on 2016/06/21 23:11:43 UTC

commons-crypto git commit: CRYPTO-73 Create example Java source code

Repository: commons-crypto
Updated Branches:
  refs/heads/master 82821524d -> d0fd391d1


CRYPTO-73 Create example Java source code

Examples created.
TODO feed these into the user guide

Project: http://git-wip-us.apache.org/repos/asf/commons-crypto/repo
Commit: http://git-wip-us.apache.org/repos/asf/commons-crypto/commit/d0fd391d
Tree: http://git-wip-us.apache.org/repos/asf/commons-crypto/tree/d0fd391d
Diff: http://git-wip-us.apache.org/repos/asf/commons-crypto/diff/d0fd391d

Branch: refs/heads/master
Commit: d0fd391d1cb4b236b6c4a1db589ebe8508f994d1
Parents: 8282152
Author: Sebb <se...@apache.org>
Authored: Wed Jun 22 00:11:40 2016 +0100
Committer: Sebb <se...@apache.org>
Committed: Wed Jun 22 00:11:40 2016 +0100

----------------------------------------------------------------------
 .../crypto/examples/CipherByteArrayExample.java | 57 +++++++++++++++
 .../examples/CipherByteBufferExample.java       | 75 ++++++++++++++++++++
 .../commons/crypto/examples/RandomExample.java  | 35 +++++++++
 .../commons/crypto/examples/StreamExample.java  | 61 ++++++++++++++++
 4 files changed, 228 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/d0fd391d/src/main/java/org/apache/commons/crypto/examples/CipherByteArrayExample.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/examples/CipherByteArrayExample.java b/src/main/java/org/apache/commons/crypto/examples/CipherByteArrayExample.java
new file mode 100644
index 0000000..af2b658
--- /dev/null
+++ b/src/main/java/org/apache/commons/crypto/examples/CipherByteArrayExample.java
@@ -0,0 +1,57 @@
+package org.apache.commons.crypto.examples;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Properties;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.crypto.cipher.CipherTransformation;
+import org.apache.commons.crypto.cipher.CryptoCipher;
+import org.apache.commons.crypto.utils.Utils;
+
+public class CipherByteArrayExample {
+
+    private static byte[] getUTF8Bytes(String input) {
+        return input.getBytes(StandardCharsets.UTF_8);
+    }
+
+    public static void main(String[] args) throws Exception {
+        final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"),"AES");
+        final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
+        Properties properties = new Properties();
+        //Creates a CryptoCipher instance with the transformation and properties.
+        final CipherTransformation transform = CipherTransformation.AES_CBC_PKCS5PADDING;
+        CryptoCipher encipher = Utils.getCipherInstance(transform, properties);
+
+        final String sampleInput = "hello world!";
+        System.out.println("input:  " + sampleInput);
+
+        byte[] input = getUTF8Bytes(sampleInput);
+        byte[] output = new byte[32]; 
+
+        //Initializes the cipher with ENCRYPT_MODE, key and iv.
+        encipher.init(Cipher.ENCRYPT_MODE, key, iv);
+        //Continues a multiple-part encryption/decryption operation for byte array.
+        int updateBytes = encipher.update(input, 0, input.length, output, 0);
+        System.out.println(updateBytes);
+        //We should call do final at the end of encryption/decryption.
+        int finalBytes = encipher.doFinal(input, 0, 0, output, updateBytes);
+        System.out.println(finalBytes);
+        //Closes the cipher.
+        encipher.close();
+
+        System.out.println(Arrays.toString(Arrays.copyOf(output, updateBytes+finalBytes)));
+
+        // Now reverse the process
+        CryptoCipher decipher = Utils.getCipherInstance(transform, properties);
+        decipher.init(Cipher.DECRYPT_MODE, key, iv);
+        byte [] decoded = new byte[32];
+        decipher.doFinal(output, 0, updateBytes + finalBytes, decoded, 0);
+
+        System.out.println("output: " + new String(decoded, StandardCharsets.UTF_8));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/d0fd391d/src/main/java/org/apache/commons/crypto/examples/CipherByteBufferExample.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/examples/CipherByteBufferExample.java b/src/main/java/org/apache/commons/crypto/examples/CipherByteBufferExample.java
new file mode 100644
index 0000000..5b2c1fb
--- /dev/null
+++ b/src/main/java/org/apache/commons/crypto/examples/CipherByteBufferExample.java
@@ -0,0 +1,75 @@
+package org.apache.commons.crypto.examples;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Properties;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.crypto.cipher.CipherTransformation;
+import org.apache.commons.crypto.cipher.CryptoCipher;
+import org.apache.commons.crypto.utils.Utils;
+
+public class CipherByteBufferExample {
+
+    private static byte[] getUTF8Bytes(String input) {
+        return input.getBytes(StandardCharsets.UTF_8);
+    }
+
+    private static String asString(ByteBuffer buffer, boolean flip) {
+        final ByteBuffer copy = buffer.duplicate();
+        if (flip) {
+            copy.flip();
+        }
+        final byte[] bytes = new byte[Math.min(copy.remaining(),50)];
+        copy.get(bytes);
+        return new String(bytes, StandardCharsets.UTF_8);
+    }
+
+    public static void main(String[] args) throws Exception {
+        final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"), "AES");
+        final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
+        Properties properties = new Properties();
+        //Creates a CryptoCipher instance with the transformation and properties.
+        final CipherTransformation transform = CipherTransformation.AES_CBC_PKCS5PADDING;
+        CryptoCipher encipher = Utils.getCipherInstance(transform, properties);
+
+        final int bufferSize = 1024;
+
+        ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
+        ByteBuffer outBuffer = ByteBuffer.allocateDirect(bufferSize);
+        inBuffer.put(getUTF8Bytes("hello world!"));
+        // Show the data is there
+        System.out.println("inBuffer="+asString(inBuffer, true));
+
+        inBuffer.flip(); // ready for the cipher to read it
+        // Initializes the cipher with ENCRYPT_MODE,key and iv.
+        encipher.init(Cipher.ENCRYPT_MODE, key, iv);
+        // Continues a multiple-part encryption/decryption operation for byte buffer.
+        final int updateBytes = encipher.update(inBuffer, outBuffer);
+        System.out.println(updateBytes);
+
+        // We should call do final at the end of encryption/decryption.
+        final int finalBytes = encipher.doFinal(inBuffer, outBuffer);
+        System.out.println(finalBytes);
+        encipher.close();
+
+        outBuffer.flip(); // ready for use as decrypt
+        byte [] encoded = new byte[updateBytes + finalBytes];
+        outBuffer.duplicate().get(encoded);
+        System.out.println(Arrays.toString(encoded));
+
+        // Now reverse the process
+        CryptoCipher decipher = Utils.getCipherInstance(transform, properties);
+        decipher.init(Cipher.DECRYPT_MODE, key, iv);
+        ByteBuffer decoded = ByteBuffer.allocateDirect(bufferSize);
+        decipher.update(outBuffer, decoded);
+        decipher.doFinal(outBuffer, decoded);
+        decipher.close();
+        System.out.println("decoded="+asString(decoded, true));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/d0fd391d/src/main/java/org/apache/commons/crypto/examples/RandomExample.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/examples/RandomExample.java b/src/main/java/org/apache/commons/crypto/examples/RandomExample.java
new file mode 100644
index 0000000..bab54d3
--- /dev/null
+++ b/src/main/java/org/apache/commons/crypto/examples/RandomExample.java
@@ -0,0 +1,35 @@
+package org.apache.commons.crypto.examples;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.Arrays;
+import java.util.Properties;
+
+import org.apache.commons.crypto.conf.ConfigurationKeys;
+import org.apache.commons.crypto.random.CryptoRandom;
+import org.apache.commons.crypto.random.CryptoRandomFactory;
+
+public class RandomExample {
+
+    public static void main(String []args) throws GeneralSecurityException, IOException {
+        //Constructs a byte array to store random data.
+        byte[] key = new byte[16];
+        byte[] iv = new byte[16];
+        Properties properties = new Properties();
+        properties.put(ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY,
+                "org.apache.commons.crypto.random.OpensslCryptoRandom"); // TODO replace with alias
+        //Gets the 'CryptoRandom' instance.
+        CryptoRandom random = CryptoRandomFactory.getCryptoRandom(properties);
+        System.out.println(random.getClass().getCanonicalName());
+
+        //Generates random bytes and places them into the byte array.
+        random.nextBytes(key);
+        random.nextBytes(iv);
+        //Closes the CryptoRandom.
+        random.close();
+
+        // Show the output
+        System.out.println(Arrays.toString(key));
+        System.out.println(Arrays.toString(iv));
+    }
+}

http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/d0fd391d/src/main/java/org/apache/commons/crypto/examples/StreamExample.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/examples/StreamExample.java b/src/main/java/org/apache/commons/crypto/examples/StreamExample.java
new file mode 100644
index 0000000..eac4e9e
--- /dev/null
+++ b/src/main/java/org/apache/commons/crypto/examples/StreamExample.java
@@ -0,0 +1,61 @@
+package org.apache.commons.crypto.examples;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.util.Arrays;
+import java.util.Properties;
+
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.crypto.cipher.CipherTransformation;
+import org.apache.commons.crypto.stream.CryptoInputStream;
+import org.apache.commons.crypto.stream.CryptoOutputStream;
+
+/**
+ * Example showing how to use stream encryption and decryption.
+ */
+public class StreamExample {
+
+    private static byte[] getUTF8Bytes(String input) {
+        return input.getBytes(StandardCharsets.UTF_8);
+    }
+
+    public static void main(String []args) throws GeneralSecurityException, IOException {
+        final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"),"AES");
+        final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
+        Properties properties = new Properties();
+        final CipherTransformation transform = CipherTransformation.AES_CBC_PKCS5PADDING;
+
+        String input = "hello world!";
+        //Encryption with CryptoOutputStream.
+
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+
+        CryptoOutputStream cos = new CryptoOutputStream(transform, properties, outputStream, key, iv);
+        cos.write(getUTF8Bytes(input));
+        cos.flush();
+        cos.close();
+
+        // The encrypted data:
+        System.out.println("Encrypted: "+Arrays.toString(outputStream.toByteArray()));
+
+        // Decryption with CryptoInputStream.
+        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
+
+        CryptoInputStream cis = new CryptoInputStream(transform, properties, inputStream, key, iv);
+      
+        byte[] decryptedData  = new byte[1024];
+        int decryptedLen = 0;
+        int i;
+        while((i = cis.read(decryptedData, decryptedLen, decryptedData.length - decryptedLen)) > -1 ) {
+            decryptedLen += i;
+        }
+        cis.close();
+        System.out.println("Decrypted: "+new String(decryptedData, 0, decryptedLen, StandardCharsets.UTF_8));
+    }
+}