You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@turbine.apache.org by gk...@apache.org on 2019/09/03 15:14:15 UTC
svn commit: r1866324 [1/2] - in /turbine/fulcrum/trunk/yaafi-crypto: ./
src/java/org/apache/fulcrum/jce/crypto/
src/java/org/apache/fulcrum/jce/crypto/algo/
src/java/org/apache/fulcrum/jce/crypto/cli/
src/java/org/apache/fulcrum/jce/crypto/extended/ sr...
Author: gk
Date: Tue Sep 3 15:14:15 2019
New Revision: 1866324
URL: http://svn.apache.org/viewvc?rev=1866324&view=rev
Log:
- renamed and moved Main, MainJ8 classes from test folder to classes folder subpackage cli, name CLI and CLI2.
- separated parameter interface, new one CryptoParametersJ8
- moved to package extended using two cipher modes
- added log4j2 logging to test
Added:
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI2.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoParametersJ8.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Impl.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Template.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/test/log4j2.xml (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8ParameterizedTest.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8Test.java (with props)
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/Main8Test.java (with props)
Removed:
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryJ8.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryJ8Impl.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryJ8Template.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoUtilJ8.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/MainJ8.java
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/CryptoUtilJ8ParameterizedTest.java
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/CryptoUtilJ8Test.java
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/Main.java
Modified:
turbine/fulcrum/trunk/yaafi-crypto/pom.xml
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoParameters.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryImpl.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoUtil.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamGCMImpl.java
turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamPBEImpl.java
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/CryptoUtilTest.java
turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/MainTest.java
Modified: turbine/fulcrum/trunk/yaafi-crypto/pom.xml
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/pom.xml?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/pom.xml (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/pom.xml Tue Sep 3 15:14:15 2019
@@ -68,6 +68,12 @@
<version>1.0.8</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-core</artifactId>
+ <version>${turbine.log4j2.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
Modified: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoParameters.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoParameters.java?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoParameters.java (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoParameters.java Tue Sep 3 15:14:15 2019
@@ -30,8 +30,6 @@ public interface CryptoParameters
{
/** Parameter for PBEParameterSpec */
int COUNT = 20;
-
- int COUNT_J8 = 10_000; //200_000;
/** The password salt */
byte[] SALT = {
@@ -42,27 +40,4 @@ public interface CryptoParameters
/** The crypto algorithm being used */
String ALGORITHM = "PBEWithMD5AndDES";
- /**
- * @see https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#SunJCEProvider
- *
- * Algo/mode/padding for cipher transformation:
- * @see https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html
- *
- * PBEWithHmacSHA256AndAES_256/CBC/PKCS5Padding, PBEWithHmacSHA256AndAES_128/CBC/PKCS5Padding
- * or
- * GCM
- */
- String ALGORITHM_J8_PBE = "PBEWithHmacSHA256AndAES_256"; //"PBEWithHmacSHA256AndAES_128 ";
- String ALGORITHM_J8_GCM = "AES/GCM/NoPadding";
-
- public enum TYPES {
- PBE, GCM
- }
-
- /**
- * Prefix to decrypted hex hash to get a clue, what to use and what it is.
- *
- * This should be always 10 bytes
- */
- String CLEAR_CODE_J8 = "J8_AES256;"; //
}
Modified: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryImpl.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryImpl.java?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryImpl.java (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryImpl.java Tue Sep 3 15:14:15 2019
@@ -143,7 +143,7 @@ public class CryptoStreamFactoryImpl ext
/**
* @return Returns the algorithm.
*/
- protected String getAlgorithm()
+ public String getAlgorithm()
{
return algorithm;
}
Modified: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoUtil.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoUtil.java?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoUtil.java (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/CryptoUtil.java Tue Sep 3 15:14:15 2019
@@ -25,6 +25,8 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8;
+
/**
* Helper class to provde generic functions to work with CryptoStreams.
*
@@ -147,7 +149,7 @@ public class CryptoUtil {
throws GeneralSecurityException, IOException {
ByteArrayOutputStream bais = new ByteArrayOutputStream();
encrypt(factory, plainText, bais, password);
- return (useClearTextHeader)? CryptoParameters.CLEAR_CODE_J8 + HexConverter.toString(bais.toByteArray()):
+ return (useClearTextHeader)? CryptoParametersJ8.CLEAR_CODE_J8 + HexConverter.toString(bais.toByteArray()):
HexConverter.toString(bais.toByteArray());
}
@@ -163,7 +165,7 @@ public class CryptoUtil {
*/
public String decryptString(String cipherText, char[] password) throws GeneralSecurityException, IOException {
return decryptString(getCryptoStreamFactory(), (useClearTextHeader)?
- cipherText.substring(CryptoParameters.CLEAR_CODE_J8.length()):
+ cipherText.substring(CryptoParametersJ8.CLEAR_CODE_J8.length()):
cipherText, password);
}
Modified: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamGCMImpl.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamGCMImpl.java?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamGCMImpl.java (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamGCMImpl.java Tue Sep 3 15:14:15 2019
@@ -34,16 +34,16 @@ import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
-import org.apache.fulcrum.jce.crypto.CryptoParameters;
-import org.apache.fulcrum.jce.crypto.CryptoStreamFactoryJ8Template;
import org.apache.fulcrum.jce.crypto.StreamUtil;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8;
+import org.apache.fulcrum.jce.crypto.extended.CryptoStreamFactoryJ8Template;
/**
* Concrete implementation for creating encrypting/decrypting streams. The
* implementation uses the JCA (Java Crypto Extension) supplied
* by SUN (using SunJCE 1.42).
*
- * The implementation uses @see {@link CryptoParameters#ALGORITHM_J8_GCM} for encryption which
+ * The implementation uses @see {@link CryptoParametersJ8#ALGORITHM_J8_GCM} for encryption which
* should be sufficent for most applications.
*
* The implementation also supplies a default password in the case that
@@ -65,9 +65,9 @@ public final class CryptoStreamGCMImpl e
public CryptoStreamGCMImpl() throws GeneralSecurityException
{
this.salt = generateSalt();
- this.count = CryptoParameters.COUNT_J8;// not used
+ this.count = CryptoParametersJ8.COUNT_J8;// not used
this.providerName = PROVIDERNAME;
- this.algorithm = CryptoParameters.ALGORITHM_J8_GCM;
+ this.algorithm = CryptoParametersJ8.ALGORITHM_J8_GCM;
}
@@ -82,7 +82,7 @@ public final class CryptoStreamGCMImpl e
this.salt = salt;
this.count = count;
this.providerName = PROVIDERNAME;
- this.algorithm = CryptoParameters.ALGORITHM_J8_GCM;
+ this.algorithm = CryptoParametersJ8.ALGORITHM_J8_GCM;
}
/**
Modified: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamPBEImpl.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamPBEImpl.java?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamPBEImpl.java (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/algo/CryptoStreamPBEImpl.java Tue Sep 3 15:14:15 2019
@@ -35,16 +35,16 @@ import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
-import org.apache.fulcrum.jce.crypto.CryptoParameters;
-import org.apache.fulcrum.jce.crypto.CryptoStreamFactoryJ8Template;
import org.apache.fulcrum.jce.crypto.StreamUtil;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8;
+import org.apache.fulcrum.jce.crypto.extended.CryptoStreamFactoryJ8Template;
/**
* Concrete implementation for creating encrypting/decrypting streams. The
* implementation uses the JCA (Java Crypto Extension) supplied
* by SUN (using SunJCE 1.42).
*
- * The implementation uses as @see {@link CryptoParameters#ALGORITHM_J8_PBE} for encryption which
+ * The implementation uses as @see {@link CryptoParametersJ8#ALGORITHM_J8_PBE} for encryption which
* should be sufficent for most applications.
*
* The implementation also supplies a default password in the case that
@@ -70,9 +70,9 @@ public final class CryptoStreamPBEImpl e
public CryptoStreamPBEImpl() throws GeneralSecurityException
{
this.salt = generateSalt();
- this.count = CryptoParameters.COUNT_J8;
+ this.count = CryptoParametersJ8.COUNT_J8;
this.providerName = PROVIDERNAME;
- this.algorithm = CryptoParameters.ALGORITHM_J8_PBE;
+ this.algorithm = CryptoParametersJ8.ALGORITHM_J8_PBE;
}
/**
@@ -86,7 +86,7 @@ public final class CryptoStreamPBEImpl e
this.salt = salt;
this.count = count;
this.providerName = PROVIDERNAME;
- this.algorithm = CryptoParameters.ALGORITHM_J8_PBE;
+ this.algorithm = CryptoParametersJ8.ALGORITHM_J8_PBE;
}
/**
Added: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,185 @@
+package org.apache.fulcrum.jce.crypto.cli;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+
+import org.apache.fulcrum.jce.crypto.CryptoUtil;
+import org.apache.fulcrum.jce.crypto.StreamUtil;
+
+/**
+ * Command line tool for encrypting/decrypting files
+ *
+ * file [enc|dec] passwd [file]*
+ * string [enc|dec] passwd plaintext
+ *
+ * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl</a>
+ */
+
+public class CLI
+{
+ /**
+ * Allows testing on the command line.
+ *
+ * @param args the command line parameters
+ */
+ public static void main( String[] args )
+ {
+ try
+ {
+ if( args.length < 3 )
+ {
+ printHelp();
+ throw new IllegalArgumentException("Invalid command line");
+ }
+
+ String operationMode = args[0];
+
+ if( operationMode.equals("file") )
+ {
+ processFiles(args);
+ }
+ else if( operationMode.equals("string") )
+ {
+ processString(args);
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Error : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Prints usage information.
+ */
+ public static void printHelp()
+ {
+ System.out.println("Main file [enc|dec] passwd source [target]");
+ System.out.println("Main string [enc|dec] passwd source");
+ }
+
+ /**
+ * Decrypt/encrypt a list of files
+ * @param args the command line
+ * @throws Exception the operation failed
+ */
+ public static void processFiles(String[] args)
+ throws Exception
+ {
+ String cipherMode = args[1];
+ char[] password = args[2].toCharArray();
+ File sourceFile = new File(args[3]);
+ File targetFile = null;
+
+ if( args.length == 4 )
+ {
+ targetFile = sourceFile;
+ }
+ else
+ {
+ targetFile = new File(args[4]);
+ File parentFile = targetFile.getParentFile();
+
+ if(parentFile != null)
+ {
+ parentFile.mkdirs();
+ }
+ }
+
+ processFile(cipherMode,password,sourceFile,targetFile);
+ }
+
+ /**
+ * Decrypt/encrypt a single file
+ * @param cipherMode the mode
+ * @param password the passwors
+ * @param sourceFile the file to process
+ * @param targetFile the targetf file
+ * @throws Exception the operation failed
+ */
+ public static void processFile(String cipherMode, char[] password, File sourceFile, File targetFile)
+ throws Exception
+ {
+ try (FileInputStream fis = new FileInputStream(sourceFile)) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ if( cipherMode.equals("dec") )
+ {
+ System.out.println("Decrypting " + sourceFile.getAbsolutePath() );
+ CryptoUtil.getInstance().decrypt( fis, baos, password );
+ fis.close();
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ FileOutputStream fos = new FileOutputStream(targetFile);
+ StreamUtil.copy(bais,fos);
+ bais.close();
+ fos.close();
+ }
+ else if( cipherMode.equals("enc") )
+ {
+ System.out.println("Encrypting " + sourceFile.getAbsolutePath() );
+ CryptoUtil.getInstance().encrypt( fis, baos, password );
+ fis.close();
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ FileOutputStream fos = new FileOutputStream(targetFile);
+ StreamUtil.copy(bais,fos);
+ bais.close();
+ fos.close();
+ }
+ else
+ {
+ String msg = "Don't know what to do with : " + cipherMode;
+ throw new IllegalArgumentException(msg);
+ }
+ }
+ }
+
+ /**
+ * Decrypt/encrypt a string.
+ *
+ * @param args the command line
+ * @throws Exception the operation failed
+ */
+ public static void processString(String[] args)
+ throws Exception
+ {
+ String cipherMode = args[1];
+ char[] password = args[2].toCharArray();
+ String value = args[3];
+ String result = null;
+
+ if( cipherMode.equals("dec") )
+ {
+ result = CryptoUtil.getInstance().decryptString(value,password);
+ }
+ else
+ {
+ result = CryptoUtil.getInstance().encryptString(value,password);
+ }
+
+ System.out.println( result );
+ }
+}
\ No newline at end of file
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI2.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI2.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI2.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI2.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,199 @@
+package org.apache.fulcrum.jce.crypto.cli;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8;
+import org.apache.fulcrum.jce.crypto.extended.CryptoUtilJ8;
+
+/**
+ * Command line tool for encrypting/decrypting a file or string
+ *
+ * file [enc|dec] passwd [file]*
+ * string [enc|dec] passwd plaintext
+ *
+ * Example :
+ *
+ * java -classpath target/classes org.apache.fulcrum.jce.crypto.cli.Main string enc changeit mysecretgeheim
+ * ...
+ *
+ * java -cp target/classes org.apache.fulcrum.jce.crypto.cli.Main string dec changeit J8_AES256;<hashcode>
+ *
+ * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl</a>
+ */
+
+public class CLI2
+{
+ /**
+ * Allows usage on the command line.
+ *
+ * @param args the command line parameters
+ */
+ public static void main( String[] args )
+ {
+ try
+ {
+ if( args.length < 3 )
+ {
+ printHelp();
+ throw new IllegalArgumentException("Invalid command line");
+ }
+
+ String operationMode = args[0];
+
+
+ if( operationMode.equals("file") )
+ {
+ processFiles(args);
+ }
+ else if( operationMode.equals("string") )
+ {
+ processString(args);
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Error : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Prints usage information.
+ */
+ public static void printHelp()
+ {
+ System.out.println("\r\n*** Command line tool for encrypting/decrypting strings/files ***\r\n*** algorithm based on "+ CryptoParametersJ8.ALGORITHM_J8_PBE+ "***\r\n");
+ System.out.println( "*** Usage: ***\r\n");
+ System.out.println("java -cp target\\classes; "+ CLI2.class.getName()+ " <operation mode:file|string> <coding mode:enc|dec> <password> <path|string> [target]\r\ne.g.\r\n");
+ System.out.println( CLI2.class.getSimpleName()+ " file [enc|dec] passwd source [target]");
+ System.out.println(CLI2.class.getSimpleName() + " string [enc|dec] passwd source");
+ }
+
+ /**
+ * Decrypt/encrypt a list of files
+ * @param args the command line
+ * @throws Exception the operation failed
+ */
+ public static void processFiles(String[] args)
+ throws Exception
+ {
+ String cipherMode = args[1];
+ char[] password = args[2].toCharArray();
+ File sourceFile = new File(args[3]);
+ File targetFile = null;
+
+ if( args.length == 4 )
+ {
+ targetFile = sourceFile;
+ }
+ else
+ {
+ targetFile = new File(args[4]);
+ File parentFile = targetFile.getParentFile();
+
+ if(parentFile != null)
+ {
+ parentFile.mkdirs();
+ }
+ }
+
+ processFile(cipherMode,password,sourceFile,targetFile);
+ }
+
+ /**
+ * Decrypt/encrypt a single file
+ * @param cipherMode the mode
+ * @param password the passwors
+ * @param sourceFile the file to process
+ * @param targetFile the targetf file
+ * @throws Exception the operation failed
+ */
+ public static void processFile(String cipherMode, char[] password, File sourceFile, File targetFile)
+ throws Exception
+ {
+ FileInputStream fis = new FileInputStream(sourceFile);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ CryptoUtilJ8 cryptoUtilJ8 = CryptoUtilJ8.getInstance();
+
+ if( cipherMode.equals("dec") )
+ {
+ System.out.println("Decrypting " + sourceFile.getAbsolutePath() );
+ cryptoUtilJ8.decrypt( fis, baos, password );
+ fis.close();
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ FileOutputStream fos = new FileOutputStream(targetFile);
+ CryptoUtilJ8.copy(bais,fos);
+ bais.close();
+ fos.close();
+ }
+ else if( cipherMode.equals("enc") )
+ {
+ System.out.println("Encrypting " + sourceFile.getAbsolutePath() );
+ cryptoUtilJ8.encrypt( fis, baos, password );
+ fis.close();
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ FileOutputStream fos = new FileOutputStream(targetFile);
+ CryptoUtilJ8.copy(bais,fos);
+ bais.close();
+ fos.close();
+ }
+ else
+ {
+ String msg = "Don't know what to do with : " + cipherMode;
+ throw new IllegalArgumentException(msg);
+ }
+ }
+
+ /**
+ * Decrypt/encrypt a string.
+ *
+ * @param args the command line
+ * @throws Exception the operation failed
+ */
+ public static void processString(String[] args)
+ throws Exception
+ {
+ String cipherMode = args[1];
+ char[] password = args[2].toCharArray();
+ String value = args[3];
+ String result = null;
+
+ CryptoUtilJ8 cryptoUtilJ8 = CryptoUtilJ8.getInstance();
+
+ if( cipherMode.equals("dec") )
+ {
+ result = cryptoUtilJ8.decryptString(value,password);
+ }
+ else
+ {
+ result = cryptoUtilJ8.encryptString(value,password);
+ }
+
+ System.out.println( result );
+ }
+}
\ No newline at end of file
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/cli/CLI2.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoParametersJ8.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoParametersJ8.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoParametersJ8.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoParametersJ8.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,62 @@
+package org.apache.fulcrum.jce.crypto.extended;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+/**
+ * CryptoParameters used for encryption/decryption.
+ *
+ * @author <a href="mailto:gk@apache.org">Georg Kallidis</a>
+ */
+
+public interface CryptoParametersJ8
+{
+
+ int COUNT_J8 = 10_000; //200_000;
+
+ /**
+ * @see https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#SunJCEProvider
+ *
+ * Algo/mode/padding for cipher transformation:
+ * @see https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html
+ *
+ * using PBEWith<digest>And<encryption>:
+ *
+ * <li>PBEWithHmacSHA256AndAES_256/CBC/PKCS5Padding
+ *
+ * or
+ * Cipher Algorithm Names/Cipher Algorithm Modes/Cipher Algorithm Padding
+ *
+ * <li>AES/GCM/NoPadding
+ */
+ String ALGORITHM_J8_PBE = "PBEWithHmacSHA256AndAES_256"; //"PBEWithHmacSHA256AndAES_128 ";
+ String ALGORITHM_J8_GCM = "AES/GCM/NoPadding";
+
+ public enum TYPES {
+ PBE, GCM
+ }
+
+ /**
+ * Prefix to decrypted hex hash to get a clue, what to use and what it is.
+ *
+ * This should be always 10 bytes
+ */
+ String CLEAR_CODE_J8 = "J8_AES256;"; //
+}
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoParametersJ8.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,62 @@
+package org.apache.fulcrum.jce.crypto.extended;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.GeneralSecurityException;
+
+import org.apache.fulcrum.jce.crypto.CryptoStreamFactory;
+
+/**
+ * Interface for creating encrypting/decrypting streams.
+ *
+ * @author <a href="mailto:gk@apache.org">Georg Kallidis </a>
+ */
+
+public interface CryptoStreamFactoryJ8 extends CryptoStreamFactory
+{
+ /**
+ * Creates an encrypting output stream using the given password.
+ *
+ * @param is the input stream to be encoded
+ * @param os the output stream to be wrapped
+ * @param password the password to be used
+ * @return the encrypting output stream
+ * @throws GeneralSecurityException creating the output stream failed
+ * @throws IOException creating the output stream failed
+ */
+ OutputStream getOutputStream(InputStream is, OutputStream os, char[] password)
+ throws GeneralSecurityException, IOException;
+
+ /**
+ * Creates input stream based on the decryption mode
+ * using the default password.
+ *
+ * @param is the input stream to be wrapped
+ * @param decryptionMode the decryption mode (true|false|auto)
+ * @return an decrypting input stream
+ * @throws GeneralSecurityException creating the input stream failed
+ * @throws IOException creating the input stream failed
+ */
+ InputStream getInputStream(InputStream is, char[] password)
+ throws GeneralSecurityException, IOException;
+}
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Impl.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Impl.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Impl.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Impl.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,297 @@
+package org.apache.fulcrum.jce.crypto.extended;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.AlgorithmParameters;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+
+import org.apache.fulcrum.jce.crypto.CryptoStreamFactory;
+import org.apache.fulcrum.jce.crypto.CryptoStreamFactoryImpl;
+import org.apache.fulcrum.jce.crypto.PasswordFactory;
+import org.apache.fulcrum.jce.crypto.StreamUtil;
+
+/**
+ * Concrete factory for creating encrypting/decrypting streams. The
+ * implementation uses the JCA (Java Crypto Extension) supplied
+ * by SUN (using SunJCE 1.42).
+ *
+ * The implementation uses as PBEWithHmacSHA256AndAES_256, see {@link CryptoParametersJ8#ALGORITHM_J8} for encryption which
+ * should be sufficent for most applications.
+ *
+ * The implementation also supplies a default password in the case that
+ * the programmer don't want to have additional hassles. It is easy to
+ * reengineer the password being used but much better than a hard-coded
+ * password in the application.
+ *
+ * The code uses parts from Markus Hahn's Blowfish library found at
+ * http://blowfishj.sourceforge.net/
+ *
+ * @author <a href="mailto:gk@apache.org">Georg Kallidis</a>
+ * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl </a>
+ * @author <a href="mailto:maakus@earthlink.net">Markus Hahn</a>
+ */
+@Deprecated
+public final class CryptoStreamFactoryJ8Impl extends CryptoStreamFactoryImpl implements CryptoStreamFactoryJ8
+{
+
+ private static final int SALT_SIZE = 128;//might increase cipher length
+ private static final int KEY_SIZE = 256;
+
+ /** the default instance */
+ private static CryptoStreamFactoryJ8 instance;
+
+ private AlgorithmParameters algorithmParameters;// used only for debugging
+
+
+ /**
+ * Factory method to get a default instance
+ * @return an instance of the CryptoStreamFactory
+ */
+ public synchronized static CryptoStreamFactoryJ8 getInstance()
+ {
+ if( CryptoStreamFactoryJ8Impl.instance == null )
+ {
+ try {
+ CryptoStreamFactoryJ8Impl.instance = new CryptoStreamFactoryJ8Impl();
+ } catch (GeneralSecurityException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ return CryptoStreamFactoryJ8Impl.instance;
+ }
+
+ /**
+ * Set the default instance from an external application.
+ * @param instance the new default instance
+ */
+ public static void setInstance( CryptoStreamFactoryJ8 instance )
+ {
+ CryptoStreamFactoryJ8Impl.instance = instance;
+ }
+
+ /**
+ * Constructor
+ */
+ public CryptoStreamFactoryJ8Impl() throws GeneralSecurityException
+ {
+ this.salt = generateSalt();
+ this.count = CryptoParametersJ8.COUNT_J8;
+ this.providerName = PROVIDERNAME;
+ this.algorithm = CryptoParametersJ8.ALGORITHM_J8_PBE;
+ }
+
+ /**
+ * Constructor
+ */
+ public CryptoStreamFactoryJ8Impl(String algo) throws GeneralSecurityException
+ {
+ this.salt = generateSalt();
+ this.count = CryptoParametersJ8.COUNT_J8;
+ this.providerName = PROVIDERNAME;
+ this.algorithm = algo;
+ }
+
+ /**
+ * Constructor
+ *
+ * @param salt the salt for the PBE algorithm
+ * @param count the iteration for PBEParameterSpec
+ */
+ public CryptoStreamFactoryJ8Impl( byte[] salt, int count)
+ {
+ this.salt = salt;
+ this.count = count;
+ this.providerName = PROVIDERNAME;
+ this.algorithm = CryptoParametersJ8.ALGORITHM_J8_PBE;
+ }
+
+
+ /**
+ * @see org.apache.fulcrum.jce.crypto.CryptoStreamFactory#getSmartInputStream(java.io.InputStream)
+ */
+ @Override
+ public InputStream getSmartInputStream(InputStream is)
+ throws GeneralSecurityException, IOException
+ {
+ return this.getSmartInputStream(
+ is,
+ PasswordFactory.getInstance("SHA-256").create()
+ );
+ }
+
+ /**
+ * @see org.apache.fulcrum.jce.crypto.CryptoStreamFactory#getInputStream(java.io.InputStream,char[])
+ */
+ @Override
+ public InputStream getInputStream( InputStream is, char[] password )
+ throws GeneralSecurityException, IOException
+ {
+ byte[] encrypted = this.createCipher( is, Cipher.DECRYPT_MODE, password );
+ InputStream eis = new ByteArrayInputStream(encrypted);
+ return eis;
+ }
+
+
+ @Override
+ public OutputStream getOutputStream(InputStream is, OutputStream os, char[] password)
+ throws GeneralSecurityException, IOException {
+ byte[] encrypted = this.createCipher( is, Cipher.ENCRYPT_MODE, password );
+ InputStream eis = new ByteArrayInputStream(encrypted);
+ StreamUtil.copy(eis, os);
+ return os;
+ }
+
+ /**
+ * Create a PBE key.
+ *
+ * @param password the password to use.
+ * @param salt if provided this is used, otherweise {@link #getSalt()}.
+ * @return the key
+ * @throws GeneralSecurityException creating the key failed
+ */
+ private Key createKey( char[] password, byte[] salt )
+ throws GeneralSecurityException
+ {
+ SecretKeyFactory keyFactory;
+ String algorithm = this.getAlgorithm();
+
+ PBEKeySpec keySpec = new PBEKeySpec(password, (salt == null)? this.getSalt(): salt, this.getCount(), KEY_SIZE );
+ byte[] encodedTmp = null;
+ try {
+ if( this.getProviderName() == null )
+ {
+ keyFactory = SecretKeyFactory.getInstance( algorithm );
+ }
+ else
+ {
+ keyFactory = SecretKeyFactory.getInstance( algorithm, this.getProviderName() );
+ }
+ return keyFactory.generateSecret(keySpec);
+
+ } catch (NoSuchAlgorithmException e) {
+ throw new GeneralSecurityException(e);
+ } finally {
+ if (encodedTmp != null) {
+ Arrays.fill(encodedTmp, (byte)0);
+ }
+ if (keySpec != null) {
+ keySpec.clearPassword();
+ }
+ }
+ }
+
+ /**
+ * Create a Cipher.
+ *
+ * @param mode the cipher mode
+ * @param password the password
+ * @return an instance of a cipher
+ * @throws GeneralSecurityException creating a cipher failed
+ * @throws IOException creating a cipher failed
+ */
+ private byte[] createCipher(InputStream is, int mode, char[] password )
+ throws GeneralSecurityException, IOException
+ {
+ Cipher cipher;
+ PBEParameterSpec paramSpec = null;
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
+ long total = StreamUtil.copy(is, bos);
+ byte[] input = bos.toByteArray();
+
+ byte[] ciphertext = null;
+
+ byte[] salt = null;
+ byte[] iv = null;
+ if (mode == Cipher.DECRYPT_MODE) {
+ salt = Arrays.copyOfRange(input, 0, SALT_SIZE / 8);
+ iv = Arrays.copyOfRange(input, salt.length, salt.length + 128 / 8);
+ ciphertext = Arrays.copyOfRange(input, salt.length + iv.length, input.length);// cut out salt and iv
+ }
+
+ Key key = this.createKey( password, salt );
+
+ if( this.getProviderName() == null )
+ {
+ cipher = Cipher.getInstance( this.getAlgorithm() );
+ }
+ else
+ {
+ cipher = Cipher.getInstance( this.getAlgorithm(), this.getProviderName() );
+ }
+
+ // save
+ if (mode == Cipher.DECRYPT_MODE) {
+ paramSpec = new PBEParameterSpec( salt, this.getCount(), new IvParameterSpec(iv) );
+ cipher.init( mode, key, paramSpec );
+ //cipher.init( mode, key, algorithmParameters );
+ ciphertext = cipher.doFinal(ciphertext); // actually the unencrypted bytes
+ }
+
+ // save
+ if (mode == Cipher.ENCRYPT_MODE) {
+ paramSpec = new PBEParameterSpec( this.getSalt(), this.getCount() );
+ salt = paramSpec.getSalt();
+ cipher.init( mode, key, paramSpec );
+ //algorithmParameters = cipher.getParameters();
+
+ byte[] result = cipher.doFinal(input);
+ iv = cipher.getIV(); // AES has 128bit block size
+
+ // Salt and IV need to be stored with the result, otherwise we can't decrypt the message later.
+ ciphertext = new byte[salt.length + iv.length + result.length];
+
+ System.arraycopy(salt, 0, ciphertext, 0, salt.length);
+ System.arraycopy(iv, 0, ciphertext, salt.length, iv.length);
+ System.arraycopy(result, 0, ciphertext, salt.length + iv.length, result.length);// push after salt and iv
+ }
+ return ciphertext;
+ }
+
+ private byte[] generateSalt() throws GeneralSecurityException {
+ SecureRandom random;
+ try {
+ random = SecureRandom.getInstance("SHA1PRNG");
+ byte[] salt = new byte[SALT_SIZE / 8];
+ random.nextBytes(salt);
+ return salt;
+ } catch (NoSuchAlgorithmException e) {
+ throw new GeneralSecurityException(e);
+ }
+ }
+
+}
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Impl.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Template.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Template.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Template.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Template.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,175 @@
+package org.apache.fulcrum.jce.crypto.extended;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.AlgorithmParameters;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.crypto.Cipher;
+
+import org.apache.fulcrum.jce.crypto.CryptoStreamFactoryImpl;
+import org.apache.fulcrum.jce.crypto.PasswordFactory;
+import org.apache.fulcrum.jce.crypto.StreamUtil;
+import org.apache.fulcrum.jce.crypto.algo.CryptoStreamGCMImpl;
+import org.apache.fulcrum.jce.crypto.algo.CryptoStreamPBEImpl;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8.TYPES;
+
+/**
+ * Concrete factory for creating encrypting/decrypting streams.
+ *
+ *
+ **/
+public abstract class CryptoStreamFactoryJ8Template extends CryptoStreamFactoryImpl implements CryptoStreamFactoryJ8
+{
+
+ protected static final int SALT_SIZE = 16; //might increase cipher length
+ protected static final int KEY_SIZE = 256;
+
+ /** the default instances */
+ protected static Map<TYPES,CryptoStreamFactoryJ8Template> instances = new ConcurrentHashMap();
+
+ protected AlgorithmParameters algorithmParameters;// used only for debugging
+
+ public CryptoStreamFactoryJ8Template() {
+
+ }
+
+ /**
+ * Factory method to get a default instance
+ * @return an instance of the CryptoStreamFactory
+ */
+ public static CryptoStreamFactoryJ8 getInstance(TYPES type)
+ {
+ synchronized (CryptoStreamFactoryJ8Template.class) {
+ if( !instances.containsKey(type) )
+ {
+ try {
+ instances.put(type,
+ (type.equals(TYPES.PBE))? new CryptoStreamPBEImpl():
+ new CryptoStreamGCMImpl()
+ );
+ } catch (GeneralSecurityException e) {
+ e.printStackTrace();
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ return instances.get(type);
+ }
+ }
+
+
+ /**
+ * Constructor
+ *
+ * @param salt the salt for the PBE algorithm
+ * @param count the iteration for PBEParameterSpec
+ * @paramn type {@link TYPES}
+ */
+ public CryptoStreamFactoryJ8Template( byte[] salt, int count, TYPES type)
+ {
+ this.salt = salt;
+ this.count = count;
+ this.providerName = PROVIDERNAME;
+ this.algorithm = type.equals(TYPES.PBE)? CryptoParametersJ8.ALGORITHM_J8_PBE:
+ CryptoParametersJ8.ALGORITHM_J8_GCM;
+ }
+
+
+ /**
+ * @see org.apache.fulcrum.jce.crypto.CryptoStreamFactory#getSmartInputStream(java.io.InputStream)
+ */
+ @Override
+ public InputStream getSmartInputStream(InputStream is)
+ throws GeneralSecurityException, IOException
+ {
+ return this.getSmartInputStream(
+ is,
+ PasswordFactory.getInstance("SHA-256").create()
+ );
+ }
+
+ /**
+ * @see org.apache.fulcrum.jce.crypto.CryptoStreamFactory#getInputStream(java.io.InputStream,char[])
+ */
+ @Override
+ public InputStream getInputStream( InputStream is, char[] password )
+ throws GeneralSecurityException, IOException
+ {
+ byte[] encrypted = this.createCipher( is, Cipher.DECRYPT_MODE, password );
+ InputStream eis = new ByteArrayInputStream(encrypted);
+ return eis;
+ }
+
+
+ @Override
+ public OutputStream getOutputStream(InputStream is, OutputStream os, char[] password)
+ throws GeneralSecurityException, IOException {
+ byte[] encrypted = this.createCipher( is, Cipher.ENCRYPT_MODE, password );
+ InputStream eis = new ByteArrayInputStream(encrypted);
+ StreamUtil.copy(eis, os);
+ return os;
+ }
+
+ /**
+ * Create a PBE key.
+ *
+ * @param password the password to use.
+ * @param salt if provided this is used, otherweise {@link #getSalt()}.
+ * @return the key
+ * @throws GeneralSecurityException creating the key failed
+ */
+ protected abstract Key createKey( char[] password, byte[] salt )
+ throws GeneralSecurityException;
+
+ /**
+ * Create a Cipher.
+ *
+ * @param mode the cipher mode
+ * @param password the password
+ * @return an instance of a cipher
+ * @throws GeneralSecurityException creating a cipher failed
+ * @throws IOException creating a cipher failed
+ */
+ protected abstract byte[] createCipher(InputStream is, int mode, char[] password )
+ throws GeneralSecurityException, IOException;
+
+ protected byte[] generateSalt() throws GeneralSecurityException {
+ SecureRandom random;
+ try {
+ random = SecureRandom.getInstance("SHA1PRNG");
+ byte[] salt = new byte[SALT_SIZE ];
+ random.nextBytes(salt);
+ return salt;
+ } catch (NoSuchAlgorithmException e) {
+ throw new GeneralSecurityException(e);
+ }
+ }
+
+}
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoStreamFactoryJ8Template.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,147 @@
+package org.apache.fulcrum.jce.crypto.extended;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.GeneralSecurityException;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.fulcrum.jce.crypto.CryptoStreamFactory;
+import org.apache.fulcrum.jce.crypto.CryptoUtil;
+import org.apache.fulcrum.jce.crypto.StreamUtil;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8.TYPES;
+
+/**
+ * Helper class to provde generic functions to work with CryptoStreams.
+ *
+ * The code uses parts from Markus Hahn's Blowfish library found at
+ * http://blowfishj.sourceforge.net/
+ *
+ * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl </a>
+ * @author <a href="mailto:maakus@earthlink.net">Markus Hahn</a>
+ */
+
+public final class CryptoUtilJ8 extends CryptoUtil {
+
+
+ public TYPES type;// default see instance
+
+
+ public TYPES getType() {
+ return type;
+ }
+
+ /** the typed default instances */
+ private static Map<TYPES,CryptoUtilJ8> cryptoUtilJ8s = new ConcurrentHashMap();
+
+
+ /**
+ * Factory method to get a default instance
+ * @param type
+ * @return an instance of the CryptoStreamFactory
+ */
+ public static CryptoUtilJ8 getInstance(TYPES type)
+ {
+ synchronized (CryptoUtilJ8.class) {
+ if( !cryptoUtilJ8s.containsKey(type) )
+ {
+ cryptoUtilJ8s.put(type, new CryptoUtilJ8(type) );
+ }
+
+ return cryptoUtilJ8s.get(type);
+ }
+ }
+
+ /**
+ * Factory method to get a default instance
+ *
+ * default type PDC
+ * @return an instance of the CryptoStreamFactory
+ */
+ public static CryptoUtilJ8 getInstance()
+ {
+ synchronized (CryptoUtilJ8.class) {
+ if( cryptoUtilJ8s.isEmpty() && !cryptoUtilJ8s.containsKey(TYPES.PBE) )
+ {
+ cryptoUtilJ8s.put(TYPES.PBE, new CryptoUtilJ8(TYPES.PBE) );
+ }
+
+ return cryptoUtilJ8s.get(TYPES.PBE);
+ }
+ }
+
+ public CryptoUtilJ8(TYPES type) {
+ this.type = type;
+ }
+
+ public CryptoUtilJ8() {
+ }
+
+ /**
+ * Copies from a source to a target object using encryption and a caller
+ * supplied CryptoStreamFactory.
+ *
+ * @param factory the factory to create the crypto streams
+ * @param source the source object
+ * @param target the target object
+ * @param password the password to use for encryption
+ * @throws GeneralSecurityException accessing JCE failed
+ * @throws IOException accessing the source failed
+ */
+ @Override
+ public void encrypt(CryptoStreamFactory factory, Object source, Object target, char[] password)
+ throws GeneralSecurityException, IOException {
+ InputStream is = StreamUtil.createInputStream(source);
+ OutputStream os = StreamUtil.createOutputStream(target);
+ OutputStream eos = ((CryptoStreamFactoryJ8)factory).getOutputStream(is, os, password);
+ // StreamUtil.copy( is, eos );
+ }
+
+ /**
+ * Copies from a source to a target object using decryption and a caller-suppier
+ * CryptoStreamFactory.
+ *
+ * @param factory the factory to create the crypto streams
+ * @param source the source object
+ * @param target the target object
+ * @param password the password to use for decryption
+ * @throws GeneralSecurityException accessing JCE failed
+ * @throws IOException accessing the source failed
+ */
+ @Override
+ public void decrypt(CryptoStreamFactory factory, Object source, Object target, char[] password)
+ throws GeneralSecurityException, IOException {
+ InputStream is = StreamUtil.createInputStream(source);
+ OutputStream os = StreamUtil.createOutputStream(target);
+ InputStream dis = factory.getInputStream(is, password);
+ StreamUtil.copy(dis, os);
+ }
+
+ /**
+ *
+ * @return the CryptoStreamFactory to be used
+ */
+ public CryptoStreamFactory getCryptoStreamFactory() {
+ return CryptoStreamFactoryJ8Template.getInstance(type);
+ }
+}
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/java/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/test/log4j2.xml
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/test/log4j2.xml?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/test/log4j2.xml (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/test/log4j2.xml Tue Sep 3 15:14:15 2019
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<Configuration status="info" verbose="false">
+ <Appenders>
+ <Console name="console" target="SYSTEM_OUT">
+ <PatternLayout pattern="%d [%t] %-5p %c - %m%n"/>
+ </Console>
+ <File name="logfile" fileName="target/fulcrum-test.log">
+ <PatternLayout pattern="%d [%t] %-5p %c - %m%n"/>
+ </File>
+ <File name="avalon" fileName="target/avalon-test.log">
+ <PatternLayout pattern="%d [%t] %-5p %c - %m%n"/>
+ </File>
+ </Appenders>
+ <Loggers>
+ <Logger name="org.apache.fulcrum.jce.crypto" level="debug" additivity="false">
+ <AppenderRef ref="console"/>
+ <AppenderRef ref="logfile"/>
+ </Logger>
+ <Logger name="org.apache.fulcrum" level="info" additivity="false">
+ <AppenderRef ref="console"/>
+ <AppenderRef ref="logfile"/>
+ </Logger>
+ <Logger name="org.apache.fulcrum.yaafi" level="info" additivity="false">
+ <AppenderRef ref="avalon"/>
+ </Logger>
+ <Logger name="avalon" level="warn" additivity="false">
+ <AppenderRef ref="avalon"/>
+ </Logger>
+ <Logger name="org.apache.logging.log4j" level="warn" additivity="false">
+ <AppenderRef ref="logfile"/>
+ </Logger>
+ <Root level="error">
+ <AppenderRef ref="console"/>
+ </Root>
+ </Loggers>
+</Configuration>
\ No newline at end of file
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/test/log4j2.xml
------------------------------------------------------------------------------
svn:eol-style = native
Modified: turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/CryptoUtilTest.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/CryptoUtilTest.java?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/CryptoUtilTest.java (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/CryptoUtilTest.java Tue Sep 3 15:14:15 2019
@@ -1,7 +1,5 @@
package org.apache.fulcrum.jce.crypto;
-import static org.junit.Assert.assertEquals;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
Modified: turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/MainTest.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/MainTest.java?rev=1866324&r1=1866323&r2=1866324&view=diff
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/MainTest.java (original)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/MainTest.java Tue Sep 3 15:14:15 2019
@@ -1,5 +1,7 @@
package org.apache.fulcrum.jce.crypto;
+import org.apache.fulcrum.jce.crypto.cli.CLI;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -55,9 +57,17 @@ public class MainTest extends TestCase
public void testStringEncryption()
{
String[] encryptionArgs = { "string", "enc", this.password, "mysecretpassword"};
- Main.main(encryptionArgs);
+ CLI.main(encryptionArgs);
String[] decryptionArgs = { "string", "dec", this.password, "9330419fc003b4e1461986782625db13f4c8c81c340a9caa"};
- Main.main(decryptionArgs);
+ CLI.main(decryptionArgs);
+ }
+
+ public void testAnotherStringEncryption()
+ {
+ String[] encryptionArgs = { "string", "enc", this.password, "secret"};
+ CLI.main(encryptionArgs);
+ String[] decryptionArgs = { "string", "dec", this.password, "39619852d48491af"};
+ CLI.main(decryptionArgs);
}
/** Encrypt a text file on the command line */
@@ -65,8 +75,8 @@ public class MainTest extends TestCase
{
String[] encryptionArgs = { "file", "enc", this.password, "./src/test/data/plain.txt", "./target/main/plain.enc.txt" };
String[] decryptionArgs = { "file", "dec", this.password, "./target/main/plain.enc.txt", "./target/main/plain.dec.txt" };
- Main.main(encryptionArgs);
- Main.main(decryptionArgs);
+ CLI.main(encryptionArgs);
+ CLI.main(decryptionArgs);
}
/** Encrypt a text file in-place on the command line */
@@ -74,8 +84,8 @@ public class MainTest extends TestCase
{
String[] encryptionArgs = { "file", "enc", this.password, "./src/test/data/plain.txt", "./target/main/plain.txt" };
String[] decryptionArgs = { "file", "dec", this.password, "./target/main/plain.txt" };
- Main.main(encryptionArgs);
- Main.main(decryptionArgs);
+ CLI.main(encryptionArgs);
+ CLI.main(decryptionArgs);
}
}
\ No newline at end of file
Added: turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8ParameterizedTest.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8ParameterizedTest.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8ParameterizedTest.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8ParameterizedTest.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,331 @@
+package org.apache.fulcrum.jce.crypto.extended;
+
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.GeneralSecurityException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.fulcrum.jce.crypto.PasswordFactory;
+import org.apache.fulcrum.jce.crypto.extended.CryptoStreamFactoryJ8Template;
+import org.apache.fulcrum.jce.crypto.extended.CryptoUtilJ8;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8.TYPES;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+
+/**
+ * Test suite for crypto functionality
+ *
+ * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl</a>
+ */
+public class CryptoUtilJ8ParameterizedTest {
+ /** the password to be used */
+ private String password;
+
+ /** the test data directory */
+ private File testDataDirectory;
+
+ /** the temp data director */
+ private File tempDataDirectory;
+
+ private List<CryptoUtilJ8> cryptoUtilJ8s = new ArrayList<>();
+
+
+ /**
+ * Constructor
+ */
+ public CryptoUtilJ8ParameterizedTest() {
+
+ this.password = "mysecret";
+ this.testDataDirectory = new File("./src/test/data");
+ this.tempDataDirectory = new File("./target/temp");
+ this.tempDataDirectory.mkdirs();
+ }
+
+
+// @ParameterizedTest
+// @EnumSource( TYPES.class )
+// public void setUp(TYPES type) throws Exception {
+// cryptoUtilJ8 = CryptoUtilJ8.getInstance(type); // (TYPES.PBE);
+// }
+
+ /**
+ * @return Returns the password.
+ */
+ protected char[] getPassword() {
+ return password.toCharArray();
+ }
+
+ /**
+ * @return Returns the tempDataDirectory.
+ */
+ protected File getTempDataDirectory() {
+ return tempDataDirectory;
+ }
+
+ /**
+ * @return Returns the testDataDirectory.
+ */
+ protected File getTestDataDirectory() {
+ return testDataDirectory;
+ }
+
+ @AfterEach
+ public void setup() {
+ cryptoUtilJ8s.clear();
+ }
+
+ /** Encrypt a text file
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testTextEncryption(TYPES type) {
+
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.txt");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.txt");
+
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ try {
+ System.out.println("checking "+ cuj8.getType());
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+ } catch (GeneralSecurityException e) {
+ e.printStackTrace();
+ fail();
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ } );
+ }
+
+ /** Decrypt a text file
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testTextDecryption(TYPES type) {
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ System.out.println("checking "+ cuj8.getType());
+ try {
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.txt");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.txt");
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+
+ File sourceFile2 = targetFile;
+ File targetFile2 = new File(this.getTempDataDirectory(), "plain.j8.dec.txt");
+ cuj8.decrypt(sourceFile2, targetFile2.getAbsolutePath(), this.getPassword());
+ assertEquals(
+ new String(Files.readAllBytes( Paths.get(sourceFile.toURI())) ),
+ new String(Files.readAllBytes( Paths.get(targetFile2.toURI())) )
+ );
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ });
+ }
+
+ /** Encrypt a PDF file
+ *
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testPdfEncryption(TYPES type) {
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.pdf");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.pdf");
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ try {
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ });
+ }
+
+ /** Decrypt a PDF file
+ *
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testPdfDecryption(TYPES type) {
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ //testPdfEncryption();
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ try {
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.pdf");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.pdf");
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+
+ File sourceFile2 = targetFile;
+ File targetFile2 = new File(this.getTempDataDirectory(), "plain.j8.dec.pdf");
+ cuj8.decrypt(sourceFile2, targetFile2, this.getPassword());
+
+ assertEquals(
+ new String(Files.readAllBytes( Paths.get(sourceFile.toURI())) ),
+ new String(Files.readAllBytes( Paths.get(targetFile2.toURI())) )
+ );
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ });
+
+ }
+
+ /** Test encryption and decryption of Strings
+ *
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testStringEncryption(TYPES type) {
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ char[] testVector = new char[513];
+
+ for (int i = 0; i < testVector.length; i++) {
+ testVector[i] = (char) i;
+ }
+
+ String source = new String(testVector);
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ String cipherText;
+ String plainText;
+ try {
+ cipherText = cuj8.encryptString(source, this.getPassword());
+ plainText = cuj8.decryptString(cipherText, this.getPassword());
+ assertEquals(source, plainText, source +" is not equal with " + plainText);
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+
+ });
+
+
+ }
+
+ /** Test encryption and decryption of Strings
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testStringHandling(TYPES type) {
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ String source = "Nobody knows the toubles I have seen ...";
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ String cipherText;
+ try {
+ cipherText = cuj8.encryptString(source, this.getPassword());
+ String plainText = cuj8.decryptString(cipherText, this.getPassword());
+ assertEquals(source, plainText);
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+
+ });
+
+ }
+
+ /** Test creating a password
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testPasswordFactory() throws Exception {
+ char[] result = null;
+ result = PasswordFactory.getInstance("SHA-256").create();
+ System.out.println("random pw:" + new String(result));
+ result = PasswordFactory.getInstance("SHA-256",10_000).create(this.getPassword());
+ System.out.println("password pw with seed:" + new String(result));
+ assertNotNull(result);
+ return;
+ }
+
+ /** Test encryption and decryption of binary data
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testBinaryHandling(TYPES type) throws Exception {
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ byte[] source = new byte[256];
+ byte[] result = null;
+
+ for (int i = 0; i < source.length; i++) {
+ source[i] = (byte) i;
+ }
+
+ ByteArrayOutputStream cipherText = new ByteArrayOutputStream();
+ ByteArrayOutputStream plainText = new ByteArrayOutputStream();
+ try {
+ cuj8.encrypt(source, cipherText, this.getPassword());
+ cuj8.decrypt(cipherText, plainText, this.getPassword());
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ result = plainText.toByteArray();
+
+ for (int i = 0; i < source.length; i++) {
+ if (source[i] != result[i]) {
+ fail("Binary data are different at position " + i);
+ }
+ }
+ });
+
+
+
+ }
+
+ /** Test encryption and decryption of Strings
+ * @throws Exception Generic exception
+ */
+ @ParameterizedTest
+ @EnumSource( TYPES.class )
+ public void testStringWithPasswordEncryption(TYPES type) {
+ char[] password = "57cb-4a23-d838-45222".toCharArray();
+ String source = "e02c-3b76-ff1e-5d9a1";
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ System.out.println("checking "+ cuj8.getType());
+ String cipherText = null;
+ try {
+ cipherText = cuj8.encryptString(source, password);
+ System.out.println(cipherText);// about 128
+
+ System.out.println("length for " + cuj8.getType() + " is:" +cipherText.length());// about 128
+ if (cuj8.type == TYPES.PBE) {
+ assertEquals(128, cipherText.length()); // 128bytes + 10 bytes for cleartext
+ }
+ CryptoStreamFactoryJ8Template.setInstance(null);
+ String plainText = cuj8.decryptString(cipherText, password);
+ assertEquals(source, plainText);
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+
+ });
+
+ }
+
+}
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8ParameterizedTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8Test.java
URL: http://svn.apache.org/viewvc/turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8Test.java?rev=1866324&view=auto
==============================================================================
--- turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8Test.java (added)
+++ turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8Test.java Tue Sep 3 15:14:15 2019
@@ -0,0 +1,329 @@
+package org.apache.fulcrum.jce.crypto.extended;
+
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.GeneralSecurityException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.fulcrum.jce.crypto.PasswordFactory;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8;
+import org.apache.fulcrum.jce.crypto.extended.CryptoStreamFactoryJ8Template;
+import org.apache.fulcrum.jce.crypto.extended.CryptoUtilJ8;
+import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8.TYPES;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+
+/**
+ * Test suite for crypto functionality
+ *
+ * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl</a>
+ */
+public class CryptoUtilJ8Test {
+ /** the password to be used */
+ private String password;
+
+ /** the test data directory */
+ private File testDataDirectory;
+
+ /** the temp data director */
+ private File tempDataDirectory;
+
+ private static List<CryptoUtilJ8> cryptoUtilJ8s = new ArrayList<>();
+
+ private static Logger log = LogManager.getLogger(CryptoUtilJ8Test.class);
+
+ /**
+ * Constructor
+ */
+ public CryptoUtilJ8Test() {
+
+ this.password = "mysecret";
+ this.testDataDirectory = new File("./src/test/data");
+ this.tempDataDirectory = new File("./target/temp");
+ this.tempDataDirectory.mkdirs();
+ }
+
+
+ @BeforeAll
+ public static void setUp() throws Exception {
+ cryptoUtilJ8s.clear();
+ for (TYPES type : CryptoParametersJ8.TYPES.values()) {
+ cryptoUtilJ8s.add(CryptoUtilJ8.getInstance(type));
+ }
+ for (CryptoUtilJ8 cryptoUtilJ8 : cryptoUtilJ8s) {
+ log.debug("registered cryptoUtilsJ8: {}", cryptoUtilJ8.getType() );
+ log.debug( ((CryptoStreamFactoryJ8Template)cryptoUtilJ8.getCryptoStreamFactory()).getAlgorithm());
+ }
+
+ }
+ @AfterAll
+ public static void destroy() {
+ cryptoUtilJ8s.clear();
+ }
+
+// @ParameterizedTest
+// @EnumSource( TYPES.class )
+// public void setUp(TYPES type) throws Exception {
+// cryptoUtilJ8 = CryptoUtilJ8.getInstance(type); // (TYPES.PBE);
+// }
+
+ /**
+ * @return Returns the password.
+ */
+ protected char[] getPassword() {
+ return password.toCharArray();
+ }
+
+ /**
+ * @return Returns the tempDataDirectory.
+ */
+ protected File getTempDataDirectory() {
+ return tempDataDirectory;
+ }
+
+ /**
+ * @return Returns the testDataDirectory.
+ */
+ protected File getTestDataDirectory() {
+ return testDataDirectory;
+ }
+
+ /** Encrypt a text file
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testTextEncryption() {
+
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.txt");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.txt");
+
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ try {
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+ } catch (GeneralSecurityException e) {
+ e.printStackTrace();
+ fail();
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ } );
+ }
+
+ /** Decrypt a text file
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testTextDecryption() {
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ try {
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.txt");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.txt");
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+
+ File sourceFile2 = new File(this.getTempDataDirectory(), "plain.j8.enc.txt");;
+ File targetFile2 = new File(this.getTempDataDirectory(), "plain.j8.dec.txt");
+ cuj8.decrypt(sourceFile2, targetFile2.getAbsolutePath(), this.getPassword());
+ assertEquals(
+ new String(Files.readAllBytes( Paths.get(sourceFile.toURI())) ),
+ new String(Files.readAllBytes( Paths.get(targetFile2.toURI())) )
+ );
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ });
+ }
+
+ /** Encrypt a PDF file
+ *
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testPdfEncryption() {
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.pdf");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.pdf");
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ try {
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ });
+ }
+
+ /** Decrypt a PDF file
+ *
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testPdfDecryption() {
+ //testPdfEncryption();
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ try {
+ File sourceFile = new File(this.getTestDataDirectory(), "plain.pdf");
+ File targetFile = new File(this.getTempDataDirectory(), "plain.j8.enc.pdf");
+ cuj8.encrypt(sourceFile, targetFile, this.getPassword());
+
+ File sourceFile2 = new File(this.getTempDataDirectory(), "plain.j8.enc.pdf");
+ File targetFile2 = new File(this.getTempDataDirectory(), "plain.j8.dec.pdf");
+ cuj8.decrypt(sourceFile2, targetFile2, this.getPassword());
+
+ assertEquals(
+ new String(Files.readAllBytes( Paths.get(sourceFile.toURI())) ),
+ new String(Files.readAllBytes( Paths.get(targetFile2.toURI())) )
+ );
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ });
+
+ }
+
+ /** Test encryption and decryption of Strings
+ *
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testStringEncryption() {
+ char[] testVector = new char[513];
+
+ for (int i = 0; i < testVector.length; i++) {
+ testVector[i] = (char) i;
+ }
+
+ String source = new String(testVector);
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ String cipherText;
+ String plainText;
+ try {
+ cipherText = cuj8.encryptString(source, this.getPassword());
+ plainText = cuj8.decryptString(cipherText, this.getPassword());
+ assertEquals(source, plainText, source +" is not equal with " + plainText);
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+
+ });
+
+
+ }
+
+ /** Test encryption and decryption of Strings
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testStringHandling() {
+ String source = "Nobody knows the toubles I have seen ...";
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ String cipherText;
+ try {
+ cipherText = cuj8.encryptString(source, this.getPassword());
+ String plainText = cuj8.decryptString(cipherText, this.getPassword());
+ assertEquals(source, plainText);
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+
+ });
+
+ }
+
+ /** Test creating a password
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testPasswordFactory() throws Exception {
+ char[] result = null;
+ result = PasswordFactory.getInstance("SHA-256").create();
+ log.debug("random pw: {}", new String(result));
+ result = PasswordFactory.getInstance("SHA-256",10_000).create(this.getPassword());
+ log.debug("password pw with seed: {}", new String(result));
+ assertNotNull(result);
+ return;
+ }
+
+ /** Test encryption and decryption of binary data
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testBinaryHandling() throws Exception {
+
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ byte[] source = new byte[256];
+ byte[] result = null;
+
+ for (int i = 0; i < source.length; i++) {
+ source[i] = (byte) i;
+ }
+
+ ByteArrayOutputStream cipherText = new ByteArrayOutputStream();
+ ByteArrayOutputStream plainText = new ByteArrayOutputStream();
+ try {
+ cuj8.encrypt(source, cipherText, this.getPassword());
+ cuj8.decrypt(cipherText, plainText, this.getPassword());
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ result = plainText.toByteArray();
+
+ for (int i = 0; i < source.length; i++) {
+ if (source[i] != result[i]) {
+ fail("Binary data are different at position " + i);
+ }
+ }
+ });
+
+
+
+ }
+
+ /** Test encryption and decryption of Strings
+ * @throws Exception Generic exception
+ */
+ @Test
+ public void testStringWithPasswordEncryption() {
+ char[] password = "57cb-4a23-d838-45222".toCharArray();
+ String source = "e02c-3b76-ff1e-5d9a1";
+
+ cryptoUtilJ8s.forEach(cuj8 -> {
+ String cipherText = null;
+ try {
+ cipherText = cuj8.encryptString(source, password);
+ log.debug(cipherText);// about 128
+
+ log.debug("length for {} is: {}", cuj8.getType(), cipherText.length());// about 128
+ if (cuj8.type == TYPES.PBE) {
+ assertEquals(128, cipherText.length()); // 128bytes + 10 bytes for cleartext
+ }
+ CryptoStreamFactoryJ8Template.setInstance(null);
+ String plainText = cuj8.decryptString(cipherText, password);
+ assertEquals(source, plainText);
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+
+ });
+
+ }
+
+}
Propchange: turbine/fulcrum/trunk/yaafi-crypto/src/test/org/apache/fulcrum/jce/crypto/extended/CryptoUtilJ8Test.java
------------------------------------------------------------------------------
svn:eol-style = native