You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by xu...@apache.org on 2016/05/04 05:45:59 UTC
[3/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java b/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
index 228cee7..df41b54 100644
--- a/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
+++ b/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
@@ -30,259 +30,257 @@ import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
/**
- * A helper to load the native code i.e. libcommons-crypto.so.
- * This handles the fallback to either the bundled libcommons-crypto-Linux-i386-32.so
- * or the default java implementations where appropriate.
+ * A helper to load the native code i.e. libcommons-crypto.so. This handles the
+ * fallback to either the bundled libcommons-crypto-Linux-i386-32.so or the
+ * default java implementations where appropriate.
*/
public class NativeCodeLoader {
- private static final Log LOG =
- LogFactory.getLog(NativeCodeLoader.class);
-
- private final static boolean nativeCodeLoaded;
+ private static final Log LOG = LogFactory.getLog(NativeCodeLoader.class);
- private NativeCodeLoader() {}
+ private final static boolean nativeCodeLoaded;
- static {
- // Try to load native library and set fallback flag appropriately
- if(LOG.isDebugEnabled()) {
- LOG.debug("Trying to load the custom-built native-commons-crypto library...");
+ private NativeCodeLoader() {
}
- boolean nativeLoaded = false;
- try {
- File nativeLibFile = findNativeLibrary();
- if (nativeLibFile != null) {
- // Load extracted or specified native library.
- System.load(nativeLibFile.getAbsolutePath());
- } else {
- // Load preinstalled library (in the path -Djava.library.path)
- System.loadLibrary("commons-crypto");
- }
- LOG.debug("Loaded the native library");
- nativeLoaded = true;
- } catch (Throwable t) {
- // Ignore failure to load
- if (LOG.isDebugEnabled()) {
- LOG.debug("Failed to load native library with error: " + t);
- LOG.debug("java.library.path=" + System.getProperty("java.library.path"));
- }
- }
+ static {
+ // Try to load native library and set fallback flag appropriately
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Trying to load the custom-built native-commons-crypto library...");
+ }
- nativeCodeLoaded = nativeLoaded;
- if (!nativeCodeLoaded) {
- LOG.warn("Unable to load native library for the platform... "
- + "using builtin-java classes where applicable");
+ boolean nativeLoaded = false;
+ try {
+ File nativeLibFile = findNativeLibrary();
+ if (nativeLibFile != null) {
+ // Load extracted or specified native library.
+ System.load(nativeLibFile.getAbsolutePath());
+ } else {
+ // Load preinstalled library (in the path -Djava.library.path)
+ System.loadLibrary("commons-crypto");
+ }
+ LOG.debug("Loaded the native library");
+ nativeLoaded = true;
+ } catch (Throwable t) {
+ // Ignore failure to load
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Failed to load native library with error: " + t);
+ LOG.debug("java.library.path="
+ + System.getProperty("java.library.path"));
+ }
+ }
+
+ nativeCodeLoaded = nativeLoaded;
+ if (!nativeCodeLoaded) {
+ LOG.warn("Unable to load native library for the platform... "
+ + "using builtin-java classes where applicable");
+ }
}
- }
- static File findNativeLibrary() {
- // Try to load the library in commons-crypto.lib.path */
- String nativeLibraryPath = Utils
- .getLibPath();
- String nativeLibraryName = Utils
- .getLibName();
+ static File findNativeLibrary() {
+ // Try to load the library in commons-crypto.lib.path */
+ String nativeLibraryPath = Utils.getLibPath();
+ String nativeLibraryName = Utils.getLibName();
- // Resolve the library file name with a suffix (e.g., dll, .so, etc.)
- if (nativeLibraryName == null) {
- nativeLibraryName = System.mapLibraryName("commons-crypto");
- }
- if (nativeLibraryPath != null) {
- File nativeLib = new File(nativeLibraryPath,
- nativeLibraryName);
- if (nativeLib.exists()) {
- return nativeLib;
- }
- }
+ // Resolve the library file name with a suffix (e.g., dll, .so, etc.)
+ if (nativeLibraryName == null) {
+ nativeLibraryName = System.mapLibraryName("commons-crypto");
+ }
+ if (nativeLibraryPath != null) {
+ File nativeLib = new File(nativeLibraryPath, nativeLibraryName);
+ if (nativeLib.exists()) {
+ return nativeLib;
+ }
+ }
- // Load an OS-dependent native library inside a jar file
- nativeLibraryPath = "/org/apache/commons/crypto/native/"
- + OSInfo.getNativeLibFolderPathForCurrentOS();
- boolean hasNativeLib = hasResource(nativeLibraryPath + "/"
- + nativeLibraryName);
- if(!hasNativeLib) {
- if (OSInfo.getOSName().equals("Mac")) {
- // Fix for openjdk7 for Mac
- String altName = "libcommons-crypto.jnilib";
- if (hasResource(nativeLibraryPath + "/" + altName)) {
- nativeLibraryName = altName;
- hasNativeLib = true;
+ // Load an OS-dependent native library inside a jar file
+ nativeLibraryPath = "/org/apache/commons/crypto/native/"
+ + OSInfo.getNativeLibFolderPathForCurrentOS();
+ boolean hasNativeLib = hasResource(nativeLibraryPath + "/"
+ + nativeLibraryName);
+ if (!hasNativeLib) {
+ if (OSInfo.getOSName().equals("Mac")) {
+ // Fix for openjdk7 for Mac
+ String altName = "libcommons-crypto.jnilib";
+ if (hasResource(nativeLibraryPath + "/" + altName)) {
+ nativeLibraryName = altName;
+ hasNativeLib = true;
+ }
+ }
}
- }
- }
- if (!hasNativeLib) {
- String errorMessage = String.format(
- "no native library is found for os.name=%s and os.arch=%s",
- OSInfo.getOSName(), OSInfo.getArchName());
- throw new RuntimeException(errorMessage);
- }
+ if (!hasNativeLib) {
+ String errorMessage = String.format(
+ "no native library is found for os.name=%s and os.arch=%s",
+ OSInfo.getOSName(), OSInfo.getArchName());
+ throw new RuntimeException(errorMessage);
+ }
+
+ // Temporary folder for the native lib. Use the value of
+ // commons-crypto.tempdir or java.io.tmpdir
+ String tempFolder = new File(Utils.getTmpDir()).getAbsolutePath();
- // Temporary folder for the native lib. Use the value of
- // commons-crypto.tempdir or java.io.tmpdir
- String tempFolder = new File(Utils.getTmpDir())
- .getAbsolutePath();
+ // Extract and load a native library inside the jar file
+ return extractLibraryFile(nativeLibraryPath, nativeLibraryName,
+ tempFolder);
+ }
- // Extract and load a native library inside the jar file
- return extractLibraryFile(nativeLibraryPath,
- nativeLibraryName, tempFolder);
- }
+ /**
+ * Extracts the specified library file to the target folder.
+ *
+ * @param libFolderForCurrentOS the library in commons-crypto.lib.path.
+ * @param libraryFileName the library name.
+ * @param targetFolder Target folder for the native lib. Use the value of
+ * commons-crypto.tempdir or java.io.tmpdir.
+ * @return the library file.
+ */
+ private static File extractLibraryFile(String libFolderForCurrentOS,
+ String libraryFileName, String targetFolder) {
+ String nativeLibraryFilePath = libFolderForCurrentOS + "/"
+ + libraryFileName;
- /**
- * Extracts the specified library file to the target folder.
- *
- * @param libFolderForCurrentOS the library in commons-crypto.lib.path.
- * @param libraryFileName the library name.
- * @param targetFolder Target folder for the native lib. Use the value of
- * commons-crypto.tempdir or java.io.tmpdir.
- * @return the library file.
- */
- private static File extractLibraryFile(String libFolderForCurrentOS,
- String libraryFileName, String targetFolder) {
- String nativeLibraryFilePath = libFolderForCurrentOS + "/"
- + libraryFileName;
+ // Attach UUID to the native library file to ensure multiple class
+ // loaders
+ // can read the libcommons-crypto multiple times.
+ String uuid = UUID.randomUUID().toString();
+ String extractedLibFileName = String.format("commons-crypto-%s-%s-%s",
+ getVersion(), uuid, libraryFileName);
+ File extractedLibFile = new File(targetFolder, extractedLibFileName);
- // Attach UUID to the native library file to ensure multiple class loaders
- // can read the libcommons-crypto multiple times.
- String uuid = UUID.randomUUID().toString();
- String extractedLibFileName = String.format("commons-crypto-%s-%s-%s", getVersion(), uuid,
- libraryFileName);
- File extractedLibFile = new File(targetFolder, extractedLibFileName);
+ InputStream reader = null;
+ try {
+ // Extract a native library file into the target directory
+ reader = NativeCodeLoader.class
+ .getResourceAsStream(nativeLibraryFilePath);
+ FileOutputStream writer = new FileOutputStream(extractedLibFile);
+ try {
+ byte[] buffer = new byte[8192];
+ int bytesRead;
+ while ((bytesRead = reader.read(buffer)) != -1) {
+ writer.write(buffer, 0, bytesRead);
+ }
+ } finally {
+ // Delete the extracted lib file on JVM exit.
+ extractedLibFile.deleteOnExit();
- InputStream reader = null;
- try {
- // Extract a native library file into the target directory
- reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
- FileOutputStream writer = new FileOutputStream(extractedLibFile);
- try {
- byte[] buffer = new byte[8192];
- int bytesRead;
- while ((bytesRead = reader.read(buffer)) != -1) {
- writer.write(buffer, 0, bytesRead);
- }
- } finally {
- // Delete the extracted lib file on JVM exit.
- extractedLibFile.deleteOnExit();
+ if (writer != null) {
+ writer.close();
+ }
- if (writer != null){
- writer.close();
- }
+ if (reader != null) {
+ reader.close();
+ reader = null;
+ }
+ }
- if (reader != null) {
- reader.close();
- reader = null;
- }
- }
+ // Set executable (x) flag to enable Java to load the native library
+ if (!extractedLibFile.setReadable(true)
+ || !extractedLibFile.setExecutable(true)
+ || !extractedLibFile.setWritable(true, true)) {
+ throw new RuntimeException("Invalid path for library path");
+ }
- // Set executable (x) flag to enable Java to load the native library
- if (!extractedLibFile.setReadable(true) || !extractedLibFile.setExecutable(true)
- || !extractedLibFile.setWritable(true, true)) {
- throw new RuntimeException("Invalid path for library path");
- }
+ // Check whether the contents are properly copied from the resource
+ // folder
+ {
+ InputStream nativeIn = null;
+ InputStream extractedLibIn = null;
+ try {
+ nativeIn = NativeCodeLoader.class
+ .getResourceAsStream(nativeLibraryFilePath);
+ extractedLibIn = new FileInputStream(extractedLibFile);
+ if (!contentsEquals(nativeIn, extractedLibIn)) {
+ throw new RuntimeException(String.format(
+ "Failed to write a native library file at %s",
+ extractedLibFile));
+ }
+ } finally {
+ if (nativeIn != null) {
+ nativeIn.close();
+ }
+ if (extractedLibIn != null) {
+ extractedLibIn.close();
+ }
+ }
+ }
- // Check whether the contents are properly copied from the resource folder
- {
- InputStream nativeIn = null;
- InputStream extractedLibIn = null;
- try {
- nativeIn =
- NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
- extractedLibIn = new FileInputStream(extractedLibFile);
- if (!contentsEquals(nativeIn, extractedLibIn)) {
- throw new RuntimeException(String.format(
- "Failed to write a native library file at %s",
- extractedLibFile));
- }
+ return new File(targetFolder, extractedLibFileName);
+ } catch (IOException e) {
+ e.printStackTrace(System.err);
+ return null;
} finally {
- if (nativeIn != null) {
- nativeIn.close();
- }
- if (extractedLibIn != null) {
- extractedLibIn.close();
- }
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
}
- }
+ }
- return new File(targetFolder, extractedLibFileName);
- } catch (IOException e) {
- e.printStackTrace(System.err);
- return null;
- } finally{
- if(reader != null){
+ /**
+ * Gets the version by reading pom.properties embedded in jar. This version
+ * data is used as a suffix of a dll file extracted from the jar.
+ *
+ * @return the version string
+ */
+ public static String getVersion() {
+ URL versionFile = NativeCodeLoader.class
+ .getResource("/META-INF/maven/org.apache.commons.crypto/commons-crypto/pom.properties");
+ if (versionFile == null) {
+ versionFile = NativeCodeLoader.class
+ .getResource("/org/apache/commons/crypto/VERSION");
+ }
+ String version = "unknown";
try {
- reader.close();
+ if (versionFile != null) {
+ Properties versionData = new Properties();
+ versionData.load(versionFile.openStream());
+ version = versionData.getProperty("version", version);
+ if (version.equals("unknown")) {
+ version = versionData.getProperty("VERSION", version);
+ }
+ version = version.trim().replaceAll("[^0-9M\\.]", "");
+ }
} catch (IOException e) {
- e.printStackTrace();
+ System.err.println(e);
}
- }
+ return version;
}
- }
- /**
- * Gets the version by reading pom.properties embedded in jar.
- * This version data is used as a suffix of a dll file extracted from the
- * jar.
- *
- * @return the version string
- */
- public static String getVersion() {
- URL versionFile = NativeCodeLoader.class
- .getResource("/META-INF/maven/org.apache.commons.crypto/commons-crypto/pom.properties");
- if (versionFile == null) {
- versionFile = NativeCodeLoader.class
- .getResource("/org/apache/commons/crypto/VERSION");
- }
- String version = "unknown";
- try {
- if (versionFile != null) {
- Properties versionData = new Properties();
- versionData.load(versionFile.openStream());
- version = versionData.getProperty("version", version);
- if (version.equals("unknown")) {
- version = versionData.getProperty("VERSION", version);
+ private static boolean contentsEquals(InputStream in1, InputStream in2)
+ throws IOException {
+ if (!(in1 instanceof BufferedInputStream)) {
+ in1 = new BufferedInputStream(in1);
+ }
+ if (!(in2 instanceof BufferedInputStream)) {
+ in2 = new BufferedInputStream(in2);
}
- version = version.trim().replaceAll("[^0-9M\\.]", "");
- }
- } catch (IOException e) {
- System.err.println(e);
- }
- return version;
- }
- private static boolean contentsEquals(InputStream in1, InputStream in2)
- throws IOException {
- if (!(in1 instanceof BufferedInputStream)) {
- in1 = new BufferedInputStream(in1);
- }
- if (!(in2 instanceof BufferedInputStream)) {
- in2 = new BufferedInputStream(in2);
+ int ch = in1.read();
+ while (ch != -1) {
+ int ch2 = in2.read();
+ if (ch != ch2) {
+ return false;
+ }
+ ch = in1.read();
+ }
+ int ch2 = in2.read();
+ return ch2 == -1;
}
- int ch = in1.read();
- while (ch != -1) {
- int ch2 = in2.read();
- if (ch != ch2) {
- return false;
- }
- ch = in1.read();
+ private static boolean hasResource(String path) {
+ return NativeCodeLoader.class.getResource(path) != null;
}
- int ch2 = in2.read();
- return ch2 == -1;
- }
- private static boolean hasResource(String path) {
- return NativeCodeLoader.class.getResource(path) != null;
- }
-
- /**
- * Checks whether native code is loaded for this platform.
- *
- * @return <code>true</code> if native is loaded,
- * else <code>false</code>.
- */
- public static boolean isNativeCodeLoaded() {
- return nativeCodeLoaded;
- }
+ /**
+ * Checks whether native code is loaded for this platform.
+ *
+ * @return <code>true</code> if native is loaded, else <code>false</code>.
+ */
+ public static boolean isNativeCodeLoaded() {
+ return nativeCodeLoaded;
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/OSInfo.java b/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
index 9d1cb88..21f2fe3 100644
--- a/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
+++ b/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
@@ -25,170 +25,184 @@ import java.util.Locale;
* Provides OS name and architecture name.
*/
public class OSInfo {
- private final static HashMap<String, String> archMapping = new HashMap<String, String>();
-
- /**
- * The constant string represents for X86 architecture, the value is: {@value #X86}.*/
- public static final String X86 = "x86";
-
- /**
- * The constant string represents for X86_64 architecture, the value is:{@value #X86_64}.*/
- public static final String X86_64 = "x86_64";
-
- /**
- * The constant string represents for IA64_32 architecture, the value is:{@value #IA64_32}.*/
- public static final String IA64_32 = "ia64_32";
-
- /**
- * The constant string represents for IA64 architecture, the value is:{@value #IA64}.*/
- public static final String IA64 = "ia64";
-
- /**
- * The constant string represents for PPC architecture, the value is:{@value #PPC}.*/
- public static final String PPC = "ppc";
-
- /**
- * The constant string represents for PPC64 architecture, the value is:{@value #PPC64}.*/
- public static final String PPC64 = "ppc64";
-
- private OSInfo() {}
-
- static {
- // x86 mappings
- archMapping.put(X86, X86);
- archMapping.put("i386", X86);
- archMapping.put("i486", X86);
- archMapping.put("i586", X86);
- archMapping.put("i686", X86);
- archMapping.put("pentium", X86);
-
- // x86_64 mappings
- archMapping.put(X86_64, X86_64);
- archMapping.put("amd64", X86_64);
- archMapping.put("em64t", X86_64);
- archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac
-
- // Itenium 64-bit mappings
- archMapping.put(IA64, IA64);
- archMapping.put("ia64w", IA64);
-
- // Itenium 32-bit mappings, usually an HP-UX construct
- archMapping.put(IA64_32, IA64_32);
- archMapping.put("ia64n", IA64_32);
-
- // PowerPC mappings
- archMapping.put(PPC, PPC);
- archMapping.put("power", PPC);
- archMapping.put("powerpc", PPC);
- archMapping.put("power_pc", PPC);
- archMapping.put("power_rs", PPC);
-
- // TODO: PowerPC 64bit mappings
- archMapping.put(PPC64, PPC64);
- archMapping.put("power64", PPC64);
- archMapping.put("powerpc64", PPC64);
- archMapping.put("power_pc64", PPC64);
- archMapping.put("power_rs64", PPC64);
- }
-
- public static void main(String[] args) {
- if (args.length >= 1) {
- if ("--os".equals(args[0])) {
- System.out.print(getOSName());
- return;
- } else if ("--arch".equals(args[0])) {
- System.out.print(getArchName());
- return;
- }
+ private final static HashMap<String, String> archMapping = new HashMap<String, String>();
+
+ /**
+ * The constant string represents for X86 architecture, the value is:
+ * {@value #X86}.
+ */
+ public static final String X86 = "x86";
+
+ /**
+ * The constant string represents for X86_64 architecture, the value is:
+ * {@value #X86_64}.
+ */
+ public static final String X86_64 = "x86_64";
+
+ /**
+ * The constant string represents for IA64_32 architecture, the value is:
+ * {@value #IA64_32}.
+ */
+ public static final String IA64_32 = "ia64_32";
+
+ /**
+ * The constant string represents for IA64 architecture, the value is:
+ * {@value #IA64}.
+ */
+ public static final String IA64 = "ia64";
+
+ /**
+ * The constant string represents for PPC architecture, the value is:
+ * {@value #PPC}.
+ */
+ public static final String PPC = "ppc";
+
+ /**
+ * The constant string represents for PPC64 architecture, the value is:
+ * {@value #PPC64}.
+ */
+ public static final String PPC64 = "ppc64";
+
+ private OSInfo() {
}
- System.out.print(getNativeLibFolderPathForCurrentOS());
- }
-
- /**
- * Gets the native lib folder.
- *
- * @return the current OS's native lib folder.
- */
- public static String getNativeLibFolderPathForCurrentOS() {
- return getOSName() + "/" + getArchName();
- }
-
- /**
- * Gets the OS name.
- *
- * @return the OS name.
- */
- public static String getOSName() {
- return translateOSNameToFolderName(System.getProperty("os.name"));
- }
-
- /**
- * Gets the architecture name.
- *
- * @return the architecture name.
- */
- public static String getArchName() {
- // if running Linux on ARM, need to determine ABI of JVM
- String osArch = System.getProperty("os.arch");
- if (osArch.startsWith("arm")
- && System.getProperty("os.name").contains("Linux")) {
- String javaHome = System.getProperty("java.home");
- try {
- // determine if first JVM found uses ARM hard-float ABI
- String[] cmdarray = {
- "/bin/sh",
- "-c",
- "find '" + javaHome
- + "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
- + "grep 'Tag_ABI_VFP_args: VFP registers'" };
- int exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
- if (exitCode == 0) {
- return "armhf";
+ static {
+ // x86 mappings
+ archMapping.put(X86, X86);
+ archMapping.put("i386", X86);
+ archMapping.put("i486", X86);
+ archMapping.put("i586", X86);
+ archMapping.put("i686", X86);
+ archMapping.put("pentium", X86);
+
+ // x86_64 mappings
+ archMapping.put(X86_64, X86_64);
+ archMapping.put("amd64", X86_64);
+ archMapping.put("em64t", X86_64);
+ archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac
+
+ // Itenium 64-bit mappings
+ archMapping.put(IA64, IA64);
+ archMapping.put("ia64w", IA64);
+
+ // Itenium 32-bit mappings, usually an HP-UX construct
+ archMapping.put(IA64_32, IA64_32);
+ archMapping.put("ia64n", IA64_32);
+
+ // PowerPC mappings
+ archMapping.put(PPC, PPC);
+ archMapping.put("power", PPC);
+ archMapping.put("powerpc", PPC);
+ archMapping.put("power_pc", PPC);
+ archMapping.put("power_rs", PPC);
+
+ // TODO: PowerPC 64bit mappings
+ archMapping.put(PPC64, PPC64);
+ archMapping.put("power64", PPC64);
+ archMapping.put("powerpc64", PPC64);
+ archMapping.put("power_pc64", PPC64);
+ archMapping.put("power_rs64", PPC64);
+ }
+
+ public static void main(String[] args) {
+ if (args.length >= 1) {
+ if ("--os".equals(args[0])) {
+ System.out.print(getOSName());
+ return;
+ } else if ("--arch".equals(args[0])) {
+ System.out.print(getArchName());
+ return;
+ }
+ }
+
+ System.out.print(getNativeLibFolderPathForCurrentOS());
+ }
+
+ /**
+ * Gets the native lib folder.
+ *
+ * @return the current OS's native lib folder.
+ */
+ public static String getNativeLibFolderPathForCurrentOS() {
+ return getOSName() + "/" + getArchName();
+ }
+
+ /**
+ * Gets the OS name.
+ *
+ * @return the OS name.
+ */
+ public static String getOSName() {
+ return translateOSNameToFolderName(System.getProperty("os.name"));
+ }
+
+ /**
+ * Gets the architecture name.
+ *
+ * @return the architecture name.
+ */
+ public static String getArchName() {
+ // if running Linux on ARM, need to determine ABI of JVM
+ String osArch = System.getProperty("os.arch");
+ if (osArch.startsWith("arm")
+ && System.getProperty("os.name").contains("Linux")) {
+ String javaHome = System.getProperty("java.home");
+ try {
+ // determine if first JVM found uses ARM hard-float ABI
+ String[] cmdarray = {
+ "/bin/sh",
+ "-c",
+ "find '"
+ + javaHome
+ + "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
+ + "grep 'Tag_ABI_VFP_args: VFP registers'" };
+ int exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
+ if (exitCode == 0) {
+ return "armhf";
+ }
+ } catch (IOException e) {
+ // ignored: fall back to "arm" arch (soft-float ABI)
+ } catch (InterruptedException e) {
+ // ignored: fall back to "arm" arch (soft-float ABI)
+ }
+ } else {
+ String lc = osArch.toLowerCase(Locale.US);
+ if (archMapping.containsKey(lc)) {
+ return archMapping.get(lc);
+ }
}
- } catch (IOException e) {
- // ignored: fall back to "arm" arch (soft-float ABI)
- } catch (InterruptedException e) {
- // ignored: fall back to "arm" arch (soft-float ABI)
- }
- } else {
- String lc = osArch.toLowerCase(Locale.US);
- if (archMapping.containsKey(lc)) {
- return archMapping.get(lc);
- }
+ return translateArchNameToFolderName(osArch);
}
- return translateArchNameToFolderName(osArch);
- }
-
- /**
- * Translates the OS name to folder name.
- *
- * @param osName the OS name.
- * @return the folder name.
- */
- static String translateOSNameToFolderName(String osName) {
- if (osName.contains("Windows")) {
- return "Windows";
- } else if (osName.contains("Mac")) {
- return "Mac";
- } else if (osName.contains("Linux")) {
- return "Linux";
- } else if (osName.contains("AIX")) {
- return "AIX";
+
+ /**
+ * Translates the OS name to folder name.
+ *
+ * @param osName the OS name.
+ * @return the folder name.
+ */
+ static String translateOSNameToFolderName(String osName) {
+ if (osName.contains("Windows")) {
+ return "Windows";
+ } else if (osName.contains("Mac")) {
+ return "Mac";
+ } else if (osName.contains("Linux")) {
+ return "Linux";
+ } else if (osName.contains("AIX")) {
+ return "AIX";
+ }
+
+ else {
+ return osName.replaceAll("\\W", "");
+ }
}
- else {
- return osName.replaceAll("\\W", "");
+ /**
+ * Translates the architecture name to folder name.
+ *
+ * @param archName the architecture name.
+ * @return the folder name.
+ */
+ static String translateArchNameToFolderName(String archName) {
+ return archName.replaceAll("\\W", "");
}
- }
-
- /**
- * Translates the architecture name to folder name.
- *
- * @param archName the architecture name.
- * @return the folder name.
- */
- static String translateArchNameToFolderName(String archName) {
- return archName.replaceAll("\\W", "");
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java b/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
index ce077d7..aab3196 100644
--- a/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
+++ b/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
@@ -30,180 +30,182 @@ import org.apache.commons.crypto.cipher.CryptoCipher;
*/
public class ReflectionUtils {
- private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>>
- CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, WeakReference<Class<?>>>>();
-
- private final static ClassLoader classLoader;
-
- static {
- ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
- classLoader = (threadClassLoader != null) ? threadClassLoader : CryptoCipher.class.getClassLoader();
- }
-
- /**
- * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}.
- */
- private static final Class<?> NEGATIVE_CACHE_SENTINEL =
- NegativeCacheSentinel.class;
-
- private ReflectionUtils() {}
-
- /**
- * A unique class which is used as a sentinel value in the caching
- * for getClassByName. {@link CryptoCipher#getClassByNameOrNull(String)}.
- */
- private static abstract class NegativeCacheSentinel {}
-
- /**
- * Uses the constructor represented by this {@code Constructor} object to
- * create and initialize a new instance of the constructor's
- * declaring class, with the specified initialization parameters.
- *
- * @param <T> type for the new instance
- * @param klass the Class object.
- * @param args array of objects to be passed as arguments to
- * the constructor call.
- * @return a new object created by calling the constructor
- * this object represents.
- */
- @SuppressWarnings("rawtypes")
- public static <T> T newInstance(Class<T> klass, Object ... args) {
- try {
- Constructor<T> ctor = null;
-
- if (args.length == 0) {
- ctor = klass.getDeclaredConstructor(new Class[] {});
- } else {
- Class[] argClses = new Class[args.length];
- for (int i = 0; i < args.length; i++) {
- argClses[i] = args[i].getClass();
- }
- ctor = klass.getDeclaredConstructor(argClses);
- }
- ctor.setAccessible(true);
- return ctor.newInstance(args);
- } catch (Exception e) {
- throw new RuntimeException(e);
+ private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>> CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, WeakReference<Class<?>>>>();
+
+ private final static ClassLoader classLoader;
+
+ static {
+ ClassLoader threadClassLoader = Thread.currentThread()
+ .getContextClassLoader();
+ classLoader = (threadClassLoader != null) ? threadClassLoader
+ : CryptoCipher.class.getClassLoader();
}
- }
-
- /**
- * Gets the value of the <code>name</code> property as a <code>Class</code>
- * implementing the interface specified by <code>xface</code>.
- * If no such property is specified, then <code>defaultValue</code> is
- * returned.An exception is thrown if the returned class does not
- * implement the named interface.
- *
- * @param <U> type for the class.
- * @param name the class name of default implementation.
- * @param defaultValue default value.
- * @param xface the interface implemented by the named class.
- * @return property value as a <code>Class</code>,
- * or <code>defaultValue</code>.
- */
- public static <U> Class<? extends U> getClass(String name,
- Class<? extends U> defaultValue,
- Class<U> xface) {
- try {
- Class<?> theClass = null;
- if (name != null && !name.isEmpty()) {
- theClass = getClassByName(name);
- }
- if (theClass == null) {
- theClass = defaultValue;
- }
- if (theClass != null && !xface.isAssignableFrom(theClass)) {
- throw new RuntimeException(theClass+" not "+xface.getName());
- } else if (theClass != null) {
- return theClass.asSubclass(xface);
- } else {
- return null;
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
+
+ /**
+ * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}.
+ */
+ private static final Class<?> NEGATIVE_CACHE_SENTINEL = NegativeCacheSentinel.class;
+
+ private ReflectionUtils() {
}
- }
-
- /**
- * Gets the value of the <code>name</code> property as a <code>Class</code>.
- * If no such property is specified, then <code>defaultValue</code> is
- * returned.
- *
- * @param name the class name.
- * @param defaultValue default value.
- * @return property value as a <code>Class</code>,
- * or <code>defaultValue</code>.
- */
- public static Class<?> getClass(String name, Class<?> defaultValue) {
- String valueString = System.getProperty(name);
- if (valueString == null) {
- return defaultValue;
+
+ /**
+ * A unique class which is used as a sentinel value in the caching for
+ * getClassByName. {@link CryptoCipher#getClassByNameOrNull(String)}.
+ */
+ private static abstract class NegativeCacheSentinel {
}
- try {
- return getClassByName(valueString);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
+
+ /**
+ * Uses the constructor represented by this {@code Constructor} object to
+ * create and initialize a new instance of the constructor's declaring
+ * class, with the specified initialization parameters.
+ *
+ * @param <T> type for the new instance
+ * @param klass the Class object.
+ * @param args array of objects to be passed as arguments to the constructor
+ * call.
+ * @return a new object created by calling the constructor this object
+ * represents.
+ */
+ @SuppressWarnings("rawtypes")
+ public static <T> T newInstance(Class<T> klass, Object... args) {
+ try {
+ Constructor<T> ctor = null;
+
+ if (args.length == 0) {
+ ctor = klass.getDeclaredConstructor(new Class[] {});
+ } else {
+ Class[] argClses = new Class[args.length];
+ for (int i = 0; i < args.length; i++) {
+ argClses[i] = args[i].getClass();
+ }
+ ctor = klass.getDeclaredConstructor(argClses);
+ }
+ ctor.setAccessible(true);
+ return ctor.newInstance(args);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
}
- }
-
- /**
- * Loads a class by name.
- *
- * @param name the class name.
- * @return the class object.
- * @throws ClassNotFoundException if the class is not found.
- */
- public static Class<?> getClassByName(String name)
- throws ClassNotFoundException {
- Class<?> ret = getClassByNameOrNull(name);
- if (ret == null) {
- throw new ClassNotFoundException("Class " + name + " not found");
+
+ /**
+ * Gets the value of the <code>name</code> property as a <code>Class</code>
+ * implementing the interface specified by <code>xface</code>. If no such
+ * property is specified, then <code>defaultValue</code> is returned.An
+ * exception is thrown if the returned class does not implement the named
+ * interface.
+ *
+ * @param <U> type for the class.
+ * @param name the class name of default implementation.
+ * @param defaultValue default value.
+ * @param xface the interface implemented by the named class.
+ * @return property value as a <code>Class</code>, or
+ * <code>defaultValue</code>.
+ */
+ public static <U> Class<? extends U> getClass(String name,
+ Class<? extends U> defaultValue, Class<U> xface) {
+ try {
+ Class<?> theClass = null;
+ if (name != null && !name.isEmpty()) {
+ theClass = getClassByName(name);
+ }
+ if (theClass == null) {
+ theClass = defaultValue;
+ }
+ if (theClass != null && !xface.isAssignableFrom(theClass)) {
+ throw new RuntimeException(theClass + " not " + xface.getName());
+ } else if (theClass != null) {
+ return theClass.asSubclass(xface);
+ } else {
+ return null;
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
}
- return ret;
- }
-
- /**
- * Loads a class by name, returning null rather than throwing an exception
- * if it couldn't be loaded. This is to avoid the overhead of creating
- * an exception.
- *
- * @param name the class name.
- * @return the class object, or null if it could not be found.
- */
- private static Class<?> getClassByNameOrNull(String name) {
- Map<String, WeakReference<Class<?>>> map;
-
- synchronized (CACHE_CLASSES) {
- map = CACHE_CLASSES.get(classLoader);
- if (map == null) {
- map = Collections.synchronizedMap(
- new WeakHashMap<String, WeakReference<Class<?>>>());
- CACHE_CLASSES.put(classLoader, map);
- }
+
+ /**
+ * Gets the value of the <code>name</code> property as a <code>Class</code>.
+ * If no such property is specified, then <code>defaultValue</code> is
+ * returned.
+ *
+ * @param name the class name.
+ * @param defaultValue default value.
+ * @return property value as a <code>Class</code>, or
+ * <code>defaultValue</code>.
+ */
+ public static Class<?> getClass(String name, Class<?> defaultValue) {
+ String valueString = System.getProperty(name);
+ if (valueString == null) {
+ return defaultValue;
+ }
+ try {
+ return getClassByName(valueString);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ }
}
- Class<?> clazz = null;
- WeakReference<Class<?>> ref = map.get(name);
- if (ref != null) {
- clazz = ref.get();
+ /**
+ * Loads a class by name.
+ *
+ * @param name the class name.
+ * @return the class object.
+ * @throws ClassNotFoundException if the class is not found.
+ */
+ public static Class<?> getClassByName(String name)
+ throws ClassNotFoundException {
+ Class<?> ret = getClassByNameOrNull(name);
+ if (ret == null) {
+ throw new ClassNotFoundException("Class " + name + " not found");
+ }
+ return ret;
}
- if (clazz == null) {
- try {
- clazz = Class.forName(name, true, classLoader);
- } catch (ClassNotFoundException e) {
- // Leave a marker that the class isn't found
- map.put(name, new WeakReference<Class<?>>(NEGATIVE_CACHE_SENTINEL));
- return null;
- }
- // two putters can race here, but they'll put the same class
- map.put(name, new WeakReference<Class<?>>(clazz));
- return clazz;
- } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
- return null; // not found
- } else {
- // cache hit
- return clazz;
+ /**
+ * Loads a class by name, returning null rather than throwing an exception
+ * if it couldn't be loaded. This is to avoid the overhead of creating an
+ * exception.
+ *
+ * @param name the class name.
+ * @return the class object, or null if it could not be found.
+ */
+ private static Class<?> getClassByNameOrNull(String name) {
+ Map<String, WeakReference<Class<?>>> map;
+
+ synchronized (CACHE_CLASSES) {
+ map = CACHE_CLASSES.get(classLoader);
+ if (map == null) {
+ map = Collections
+ .synchronizedMap(new WeakHashMap<String, WeakReference<Class<?>>>());
+ CACHE_CLASSES.put(classLoader, map);
+ }
+ }
+
+ Class<?> clazz = null;
+ WeakReference<Class<?>> ref = map.get(name);
+ if (ref != null) {
+ clazz = ref.get();
+ }
+
+ if (clazz == null) {
+ try {
+ clazz = Class.forName(name, true, classLoader);
+ } catch (ClassNotFoundException e) {
+ // Leave a marker that the class isn't found
+ map.put(name, new WeakReference<Class<?>>(
+ NEGATIVE_CACHE_SENTINEL));
+ return null;
+ }
+ // two putters can race here, but they'll put the same class
+ map.put(name, new WeakReference<Class<?>>(clazz));
+ return clazz;
+ } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
+ return null; // not found
+ } else {
+ // cache hit
+ return clazz;
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/Utils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/Utils.java b/src/main/java/org/apache/commons/crypto/utils/Utils.java
index 16ce270..17c98c2 100644
--- a/src/main/java/org/apache/commons/crypto/utils/Utils.java
+++ b/src/main/java/org/apache/commons/crypto/utils/Utils.java
@@ -47,330 +47,338 @@ import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LI
* General utility methods.
*/
public class Utils {
- private static final int MIN_BUFFER_SIZE = 512;
+ private static final int MIN_BUFFER_SIZE = 512;
- protected static final CipherTransformation AES_CTR_NOPADDING = CipherTransformation.AES_CTR_NOPADDING;
+ protected static final CipherTransformation AES_CTR_NOPADDING = CipherTransformation.AES_CTR_NOPADDING;
- /**
- * For AES, the algorithm block is fixed size of 128 bits.
- * @see <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">
- * http://en.wikipedia.org/wiki/Advanced_Encryption_Standard</a>
- */
- private static final int AES_BLOCK_SIZE = AES_CTR_NOPADDING.getAlgorithmBlockSize();
+ /**
+ * For AES, the algorithm block is fixed size of 128 bits.
+ *
+ * @see <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">
+ * http://en.wikipedia.org/wiki/Advanced_Encryption_Standard</a>
+ */
+ private static final int AES_BLOCK_SIZE = AES_CTR_NOPADDING
+ .getAlgorithmBlockSize();
- private Utils() {}
+ private Utils() {
+ }
- static {
- loadSystemProperties();
- }
+ static {
+ loadSystemProperties();
+ }
- /**
- * loads system properties when configuration file of the name
- * {@link #COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE} is found.
- */
- private static void loadSystemProperties() {
- try {
- InputStream is = Thread.currentThread().getContextClassLoader()
- .getResourceAsStream(COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE);
+ /**
+ * loads system properties when configuration file of the name
+ * {@link #COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE} is found.
+ */
+ private static void loadSystemProperties() {
+ try {
+ InputStream is = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream(COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE);
- if (is == null) {
- return; // no configuration file is found
- }
- // Load property file
- Properties props = new Properties();
- props.load(is);
- is.close();
- Enumeration<?> names = props.propertyNames();
- while (names.hasMoreElements()) {
- String name = (String) names.nextElement();
- if (name.startsWith(ConfigurationKeys.CONF_PREFIX)) {
- if (System.getProperty(name) == null) {
- System.setProperty(name, props.getProperty(name));
- }
+ if (is == null) {
+ return; // no configuration file is found
+ }
+ // Load property file
+ Properties props = new Properties();
+ props.load(is);
+ is.close();
+ Enumeration<?> names = props.propertyNames();
+ while (names.hasMoreElements()) {
+ String name = (String) names.nextElement();
+ if (name.startsWith(ConfigurationKeys.CONF_PREFIX)) {
+ if (System.getProperty(name) == null) {
+ System.setProperty(name, props.getProperty(name));
+ }
+ }
+ }
+ } catch (Throwable ex) {
+ System.err.println("Could not load '"
+ + COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE
+ + "' from classpath: " + ex.toString());
}
- }
- } catch (Throwable ex) {
- System.err.println("Could not load '"
- + COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE + "' from classpath: "
- + ex.toString());
}
- }
- /**
- * Forcibly free the direct buffer.
- *
- * @param buffer the bytebuffer to be freed.
- */
- public static void freeDirectBuffer(ByteBuffer buffer) {
- if (buffer instanceof sun.nio.ch.DirectBuffer) {
- final sun.misc.Cleaner bufferCleaner =
- ((sun.nio.ch.DirectBuffer) buffer).cleaner();
- bufferCleaner.clean();
+ /**
+ * Forcibly free the direct buffer.
+ *
+ * @param buffer the bytebuffer to be freed.
+ */
+ public static void freeDirectBuffer(ByteBuffer buffer) {
+ if (buffer instanceof sun.nio.ch.DirectBuffer) {
+ final sun.misc.Cleaner bufferCleaner = ((sun.nio.ch.DirectBuffer) buffer)
+ .cleaner();
+ bufferCleaner.clean();
+ }
}
- }
- /**
- * Reads crypto buffer size.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the buffer size.
- * */
- public static int getBufferSize(Properties props) {
- String bufferSizeStr = props.getProperty(
- COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
- if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
- bufferSizeStr = System
- .getProperty(COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
- }
- if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
- return COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT;
- } else {
- return Integer.parseInt(bufferSizeStr);
+ /**
+ * Reads crypto buffer size.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the buffer size.
+ * */
+ public static int getBufferSize(Properties props) {
+ String bufferSizeStr = props
+ .getProperty(COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
+ if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
+ bufferSizeStr = System
+ .getProperty(COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
+ }
+ if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
+ return COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT;
+ } else {
+ return Integer.parseInt(bufferSizeStr);
+ }
}
- }
- /**
- * Gets the cipher class.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the cipher class based on the props.
- */
- public static String getCipherClassString(Properties props) {
- final String configName = COMMONS_CRYPTO_CIPHER_CLASSES_KEY;
- String cipherClassString = props.getProperty(configName) != null ? props
- .getProperty(configName, COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT) : System
- .getProperty(configName, COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT);
- if (cipherClassString.isEmpty()) {
- cipherClassString = COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT;
+ /**
+ * Gets the cipher class.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the cipher class based on the props.
+ */
+ public static String getCipherClassString(Properties props) {
+ final String configName = COMMONS_CRYPTO_CIPHER_CLASSES_KEY;
+ String cipherClassString = props.getProperty(configName) != null ? props
+ .getProperty(configName, COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT)
+ : System.getProperty(configName,
+ COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT);
+ if (cipherClassString.isEmpty()) {
+ cipherClassString = COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT;
+ }
+ return cipherClassString;
}
- return cipherClassString;
- }
- /**
- * Gets the Jce provider.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the jce provider based on the props.
- */
- public static String getJCEProvider(Properties props) {
- return props.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) != null ?
- props.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) :
- System.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY);
- }
+ /**
+ * Gets the Jce provider.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the jce provider based on the props.
+ */
+ public static String getJCEProvider(Properties props) {
+ return props.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) != null ? props
+ .getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) : System
+ .getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY);
+ }
- /**
- * Gets the random device path.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the random device path based on the props.
- */
- public static String getRandomDevPath(Properties props) {
- String devPath = props.getProperty(
- COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY);
- if (devPath == null) {
- devPath = System.getProperty(
- COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY,
- COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT);
+ /**
+ * Gets the random device path.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the random device path based on the props.
+ */
+ public static String getRandomDevPath(Properties props) {
+ String devPath = props
+ .getProperty(COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY);
+ if (devPath == null) {
+ devPath = System.getProperty(
+ COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY,
+ COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT);
+ }
+ return devPath;
}
- return devPath;
- }
- /**
- * Gets path of native library.
- *
- * @return the path of native library.
- */
- public static String getLibPath() {
- return System.getProperty(COMMONS_CRYPTO_LIB_PATH_KEY);
- }
+ /**
+ * Gets path of native library.
+ *
+ * @return the path of native library.
+ */
+ public static String getLibPath() {
+ return System.getProperty(COMMONS_CRYPTO_LIB_PATH_KEY);
+ }
- /**
- * Gets the file name of native library.
- *
- * @return the file name of native library.
- */
- public static String getLibName() {
- return System.getProperty(COMMONS_CRYPTO_LIB_NAME_KEY);
- }
+ /**
+ * Gets the file name of native library.
+ *
+ * @return the file name of native library.
+ */
+ public static String getLibName() {
+ return System.getProperty(COMMONS_CRYPTO_LIB_NAME_KEY);
+ }
- /**
- * Gets the temp directory for extracting crypto library.
- *
- * @return the temp directory.
- */
- public static String getTmpDir() {
- return System.getProperty(COMMONS_CRYPTO_LIB_TEMPDIR_KEY,
- System.getProperty("java.io.tmpdir"));
- }
+ /**
+ * Gets the temp directory for extracting crypto library.
+ *
+ * @return the temp directory.
+ */
+ public static String getTmpDir() {
+ return System.getProperty(COMMONS_CRYPTO_LIB_TEMPDIR_KEY,
+ System.getProperty("java.io.tmpdir"));
+ }
- /**
- * Checks whether the cipher is supported streaming.
- *
- * @param cipher the {@link CryptoCipher} instance.
- * @throws IOException if an I/O error occurs.
- */
- public static void checkStreamCipher(CryptoCipher cipher) throws IOException {
- if (cipher.getTransformation() != CipherTransformation.AES_CTR_NOPADDING) {
- throw new IOException("AES/CTR/NoPadding is required");
+ /**
+ * Checks whether the cipher is supported streaming.
+ *
+ * @param cipher the {@link CryptoCipher} instance.
+ * @throws IOException if an I/O error occurs.
+ */
+ public static void checkStreamCipher(CryptoCipher cipher)
+ throws IOException {
+ if (cipher.getTransformation() != CipherTransformation.AES_CTR_NOPADDING) {
+ throw new IOException("AES/CTR/NoPadding is required");
+ }
}
- }
- /**
- * Checks and floors buffer size.
- *
- * @param cipher the {@link CryptoCipher} instance.
- * @param bufferSize the buffer size.
- * @return the remaining buffer size.
- */
- public static int checkBufferSize(CryptoCipher cipher, int bufferSize) {
- checkArgument(bufferSize >= MIN_BUFFER_SIZE,
- "Minimum value of buffer size is " + MIN_BUFFER_SIZE + ".");
- return bufferSize - bufferSize % cipher.getTransformation()
- .getAlgorithmBlockSize();
- }
+ /**
+ * Checks and floors buffer size.
+ *
+ * @param cipher the {@link CryptoCipher} instance.
+ * @param bufferSize the buffer size.
+ * @return the remaining buffer size.
+ */
+ public static int checkBufferSize(CryptoCipher cipher, int bufferSize) {
+ checkArgument(bufferSize >= MIN_BUFFER_SIZE,
+ "Minimum value of buffer size is " + MIN_BUFFER_SIZE + ".");
+ return bufferSize - bufferSize
+ % cipher.getTransformation().getAlgorithmBlockSize();
+ }
- /**
- * <p>
- * This method is only for Counter (CTR) mode. Generally the CryptoCipher calculates the
- * IV and maintain encryption context internally.For example a Cipher will maintain its
- * encryption context internally when we do encryption/decryption using the
- * CryptoCipher#update interface.
- * </p>
- * <p>
- * Encryption/Decryption is not always on the entire file. For example,
- * in Hadoop, a node may only decrypt a portion of a file (i.e. a split).
- * In these situations, the counter is derived from the file position.
- * </p>
- * The IV can be calculated by combining the initial IV and the counter with
- * a lossless operation (concatenation, addition, or XOR).
- *
- * @see <a href="http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29">
- * http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29</a>
- *
- * @param initIV initial IV
- * @param counter counter for input stream position
- * @param IV the IV for input stream position
- */
- public static void calculateIV(byte[] initIV, long counter, byte[] IV) {
- checkArgument(initIV.length == AES_BLOCK_SIZE);
- checkArgument(IV.length == AES_BLOCK_SIZE);
+ /**
+ * <p>
+ * This method is only for Counter (CTR) mode. Generally the CryptoCipher
+ * calculates the IV and maintain encryption context internally.For example
+ * a Cipher will maintain its encryption context internally when we do
+ * encryption/decryption using the CryptoCipher#update interface.
+ * </p>
+ * <p>
+ * Encryption/Decryption is not always on the entire file. For example, in
+ * Hadoop, a node may only decrypt a portion of a file (i.e. a split). In
+ * these situations, the counter is derived from the file position.
+ * </p>
+ * The IV can be calculated by combining the initial IV and the counter with
+ * a lossless operation (concatenation, addition, or XOR).
+ *
+ * @see <a
+ * href="http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29">
+ * http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29</a>
+ *
+ * @param initIV initial IV
+ * @param counter counter for input stream position
+ * @param IV the IV for input stream position
+ */
+ public static void calculateIV(byte[] initIV, long counter, byte[] IV) {
+ checkArgument(initIV.length == AES_BLOCK_SIZE);
+ checkArgument(IV.length == AES_BLOCK_SIZE);
- int i = IV.length; // IV length
- int j = 0; // counter bytes index
- int sum = 0;
- while (i-- > 0) {
- // (sum >>> Byte.SIZE) is the carry for addition
- sum = (initIV[i] & 0xff) + (sum >>> Byte.SIZE);
- if (j++ < 8) { // Big-endian, and long is 8 bytes length
- sum += (byte) counter & 0xff;
- counter >>>= 8;
- }
- IV[i] = (byte) sum;
+ int i = IV.length; // IV length
+ int j = 0; // counter bytes index
+ int sum = 0;
+ while (i-- > 0) {
+ // (sum >>> Byte.SIZE) is the carry for addition
+ sum = (initIV[i] & 0xff) + (sum >>> Byte.SIZE);
+ if (j++ < 8) { // Big-endian, and long is 8 bytes length
+ sum += (byte) counter & 0xff;
+ counter >>>= 8;
+ }
+ IV[i] = (byte) sum;
+ }
}
- }
- /**
- * Helper method to create a CryptoCipher instance and throws only IOException.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param transformation the CipherTransformation instance.
- * @return the CryptoCipher instance.
- * @throws IOException if an I/O error occurs.
- */
- public static CryptoCipher getCipherInstance(CipherTransformation transformation,
- Properties props) throws IOException {
- try {
- return CryptoCipherFactory.getInstance(transformation, props);
- } catch (GeneralSecurityException e) {
- throw new IOException(e);
+ /**
+ * Helper method to create a CryptoCipher instance and throws only
+ * IOException.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param transformation the CipherTransformation instance.
+ * @return the CryptoCipher instance.
+ * @throws IOException if an I/O error occurs.
+ */
+ public static CryptoCipher getCipherInstance(
+ CipherTransformation transformation, Properties props)
+ throws IOException {
+ try {
+ return CryptoCipherFactory.getInstance(transformation, props);
+ } catch (GeneralSecurityException e) {
+ throw new IOException(e);
+ }
}
- }
- /**
- * Ensures the truth of an expression involving one or more parameters to
- * the calling method.
- *
- * @param expression a boolean expression.
- * @throws IllegalArgumentException if expression is false.
- */
- public static void checkArgument(boolean expression) {
- if(!expression) {
- throw new IllegalArgumentException();
+ /**
+ * Ensures the truth of an expression involving one or more parameters to
+ * the calling method.
+ *
+ * @param expression a boolean expression.
+ * @throws IllegalArgumentException if expression is false.
+ */
+ public static void checkArgument(boolean expression) {
+ if (!expression) {
+ throw new IllegalArgumentException();
+ }
}
- }
- /**
- * Checks the truth of an expression.
- *
- * @param expression a boolean expression.
- * @param errorMessage the exception message to use if the check fails;
- * will be converted to a string using <code>String
- * .valueOf(Object)</code>.
- * @throws IllegalArgumentException if expression is false.
- */
- public static void checkArgument(boolean expression, Object errorMessage) {
- if (!expression) {
- throw new IllegalArgumentException(String.valueOf(errorMessage));
+ /**
+ * Checks the truth of an expression.
+ *
+ * @param expression a boolean expression.
+ * @param errorMessage the exception message to use if the check fails; will
+ * be converted to a string using <code>String
+ * .valueOf(Object)</code>.
+ * @throws IllegalArgumentException if expression is false.
+ */
+ public static void checkArgument(boolean expression, Object errorMessage) {
+ if (!expression) {
+ throw new IllegalArgumentException(String.valueOf(errorMessage));
+ }
}
- }
- /**
- * Ensures that an object reference passed as a parameter to the calling
- * method is not null.
- *
- * @param <T> the type of the object reference to be checked.
- * @param reference an object reference.
- * @return the non-null reference that was validated.
- * @throws NullPointerException if reference is null.
- */
- public static <T> T checkNotNull(T reference) {
- if(reference == null) {
- throw new NullPointerException();
- } else {
- return reference;
+ /**
+ * Ensures that an object reference passed as a parameter to the calling
+ * method is not null.
+ *
+ * @param <T> the type of the object reference to be checked.
+ * @param reference an object reference.
+ * @return the non-null reference that was validated.
+ * @throws NullPointerException if reference is null.
+ */
+ public static <T> T checkNotNull(T reference) {
+ if (reference == null) {
+ throw new NullPointerException();
+ } else {
+ return reference;
+ }
}
- }
- /**
- * Ensures the truth of an expression involving the state of the calling
- * instance, but not involving any parameters to the calling method.
- *
- * @param expression a boolean expression.
- * @throws IllegalStateException if expression is false.
- */
- public static void checkState(boolean expression) {
- if(!expression) {
- throw new IllegalStateException();
+ /**
+ * Ensures the truth of an expression involving the state of the calling
+ * instance, but not involving any parameters to the calling method.
+ *
+ * @param expression a boolean expression.
+ * @throws IllegalStateException if expression is false.
+ */
+ public static void checkState(boolean expression) {
+ if (!expression) {
+ throw new IllegalStateException();
+ }
}
- }
- /**
- * Splits class names sequence into substrings, Trim each substring into an
- * entry,and returns an list of the entries.
- *
- * @param clazzNames a string consist of a list of the entries joined by a
- * delimiter.
- * @param separator a delimiter for the input string.
- * @return a list of class entries.
- */
- public static List<String> splitClassNames(String clazzNames,
- String separator) {
- List<String> res = new ArrayList<String>();
- if (clazzNames == null || clazzNames.isEmpty()) {
- return res;
- }
+ /**
+ * Splits class names sequence into substrings, Trim each substring into an
+ * entry,and returns an list of the entries.
+ *
+ * @param clazzNames a string consist of a list of the entries joined by a
+ * delimiter.
+ * @param separator a delimiter for the input string.
+ * @return a list of class entries.
+ */
+ public static List<String> splitClassNames(String clazzNames,
+ String separator) {
+ List<String> res = new ArrayList<String>();
+ if (clazzNames == null || clazzNames.isEmpty()) {
+ return res;
+ }
- for (String clazzName : clazzNames.split(separator)) {
- clazzName = clazzName.trim();
- if (!clazzName.isEmpty()) {
- res.add(clazzName);
- }
+ for (String clazzName : clazzNames.split(separator)) {
+ clazzName = clazzName.trim();
+ if (!clazzName.isEmpty()) {
+ res.add(clazzName);
+ }
+ }
+ return res;
}
- return res;
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/package-info.java b/src/main/java/org/apache/commons/crypto/utils/package-info.java
index 7a3c334..20785f2 100644
--- a/src/main/java/org/apache/commons/crypto/utils/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/utils/package-info.java
@@ -19,3 +19,4 @@
* Utils classes
*/
package org.apache.commons.crypto.utils;
+
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java b/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
index f60f29c..00d1505 100644
--- a/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
+++ b/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
@@ -36,209 +36,229 @@ import org.junit.Test;
public abstract class AbstractCipherTest {
- // data
- public static final int BYTEBUFFER_SIZE = 1000;
- public String[] cipherTests = null;
- Properties props = null;
- String cipherClass = null;
- CipherTransformation[] transformations = null;
-
- // cipher
- static final byte[] KEY = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
- 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
- static final byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
- 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
- CryptoCipher enc, dec;
-
- @Before
- public void setup() {
- init();
- Utils.checkNotNull(cipherClass);
- Utils.checkNotNull(transformations);
- props = new Properties();
- props.setProperty(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
- cipherClass);
- }
-
- protected abstract void init() ;
-
- @Test
- public void cryptoTest() throws GeneralSecurityException, IOException {
- for (CipherTransformation tran : transformations) {
- /** uses the small data set in {@link TestData} */
- cipherTests = TestData.getTestData(tran);
- for (int i = 0; i != cipherTests.length; i += 5) {
- byte[] key = DatatypeConverter.parseHexBinary(cipherTests[i + 1]);
- byte[] iv = DatatypeConverter.parseHexBinary(cipherTests[i + 2]);
-
- byte[] inputBytes = DatatypeConverter.parseHexBinary(cipherTests[i + 3]);
- byte[] outputBytes = DatatypeConverter.parseHexBinary(cipherTests[i + 4]);
-
- ByteBuffer inputBuffer = ByteBuffer.allocateDirect(inputBytes.length);
- ByteBuffer outputBuffer = ByteBuffer.allocateDirect(outputBytes.length);
- inputBuffer.put(inputBytes);
- inputBuffer.flip();
- outputBuffer.put(outputBytes);
- outputBuffer.flip();
-
- byteBufferTest(tran,key, iv, inputBuffer, outputBuffer);
- byteArrayTest(tran, key, iv, inputBytes, outputBytes);
- }
-
- /** uses randomly generated big data set */
- byteArrayTest(tran, KEY, IV);
- }
- }
-
- private void byteBufferTest(CipherTransformation transformation, byte[] key,
- byte[] iv,
- ByteBuffer input, ByteBuffer output) throws
- GeneralSecurityException, IOException {
- ByteBuffer decResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
- ByteBuffer encResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
+ // data
+ public static final int BYTEBUFFER_SIZE = 1000;
+ public String[] cipherTests = null;
+ Properties props = null;
+ String cipherClass = null;
+ CipherTransformation[] transformations = null;
+
+ // cipher
+ static final byte[] KEY = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
+ static final byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
CryptoCipher enc, dec;
- enc = getCipher(transformation);
- dec = getCipher(transformation);
-
- try {
- enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
+ @Before
+ public void setup() {
+ init();
+ Utils.checkNotNull(cipherClass);
+ Utils.checkNotNull(transformations);
+ props = new Properties();
+ props.setProperty(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
+ cipherClass);
}
- try {
- dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
+ protected abstract void init();
+
+ @Test
+ public void cryptoTest() throws GeneralSecurityException, IOException {
+ for (CipherTransformation tran : transformations) {
+ /** uses the small data set in {@link TestData} */
+ cipherTests = TestData.getTestData(tran);
+ for (int i = 0; i != cipherTests.length; i += 5) {
+ byte[] key = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 1]);
+ byte[] iv = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 2]);
+
+ byte[] inputBytes = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 3]);
+ byte[] outputBytes = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 4]);
+
+ ByteBuffer inputBuffer = ByteBuffer
+ .allocateDirect(inputBytes.length);
+ ByteBuffer outputBuffer = ByteBuffer
+ .allocateDirect(outputBytes.length);
+ inputBuffer.put(inputBytes);
+ inputBuffer.flip();
+ outputBuffer.put(outputBytes);
+ outputBuffer.flip();
+
+ byteBufferTest(tran, key, iv, inputBuffer, outputBuffer);
+ byteArrayTest(tran, key, iv, inputBytes, outputBytes);
+ }
+
+ /** uses randomly generated big data set */
+ byteArrayTest(tran, KEY, IV);
+ }
}
- //
- // encryption pass
- //
- enc.doFinal(input, encResult);
- input.flip();
- encResult.flip();
- if (!output.equals(encResult)) {
- byte[] b = new byte[output.remaining()];
- output.get(b);
- byte[] c = new byte[encResult.remaining()];
- encResult.get(c);
- Assert.fail("AES failed encryption - expected " + new String(
- DatatypeConverter
- .printHexBinary(b)) + " got " + new String(
- DatatypeConverter.printHexBinary(c)));
- }
+ private void byteBufferTest(CipherTransformation transformation,
+ byte[] key, byte[] iv, ByteBuffer input, ByteBuffer output)
+ throws GeneralSecurityException, IOException {
+ ByteBuffer decResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
+ ByteBuffer encResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
+ CryptoCipher enc, dec;
+
+ enc = getCipher(transformation);
+ dec = getCipher(transformation);
+
+ try {
+ enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
- //
- // decryption pass
- //
- dec.doFinal(encResult, decResult);
- decResult.flip();
-
- if (!input.equals(decResult)) {
- byte[] inArray = new byte[input.remaining()];
- byte[] decResultArray = new byte[decResult.remaining()];
- input.get(inArray);
- decResult.get(decResultArray);
- Assert.fail();
- }
- }
-
- /** test byte array whose data is planned in {@link TestData} */
- private void byteArrayTest(CipherTransformation transformation, byte[] key,
- byte[] iv, byte[] input, byte[] output) throws GeneralSecurityException {
- resetCipher(transformation, key, iv);
- int blockSize = transformation.getAlgorithmBlockSize();
-
- byte[] temp = new byte[input.length + blockSize];
- int n = enc.doFinal(input, 0, input.length, temp, 0);
- byte[] cipherText = new byte[n];
- System.arraycopy(temp, 0, cipherText, 0, n);
- Assert.assertArrayEquals("byte array encryption error.", output, cipherText);
-
- temp = new byte[cipherText.length + blockSize];
- int m = dec.doFinal(cipherText, 0, cipherText.length, temp, 0);
- byte[] plainText = new byte[m];
- System.arraycopy(temp, 0, plainText, 0, m);
- Assert.assertArrayEquals("byte array decryption error.", input, plainText);
- }
-
- /** test byte array whose data is randomly generated */
- private void byteArrayTest(CipherTransformation transformation, byte[] key,
- byte[] iv) throws GeneralSecurityException {
- int blockSize = transformation.getAlgorithmBlockSize();
-
- // AES_CBC_NOPADDING only accepts data whose size is the multiple of block size
- int[] dataLenList = (transformation == CipherTransformation.AES_CBC_NOPADDING)
- ? new int[] {10 * 1024} : new int[] {10 * 1024, 10 * 1024 - 3};
- for (int dataLen : dataLenList) {
- byte[] plainText = new byte[dataLen];
- Random random = new SecureRandom();
- random.nextBytes(plainText);
- byte[] cipherText = new byte[dataLen + blockSize];
-
- // check update method with inputs whose sizes are the multiple of block size or not
- int[] bufferLenList = new int[] {2 * 1024 - 128, 2 * 1024 - 125};
- for (int bufferLen : bufferLenList) {
- resetCipher(transformation, key, iv);
+ try {
+ dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
- int offset = 0;
- // encrypt (update + doFinal) the data
- int cipherPos = 0;
- for (int i = 0; i < dataLen / bufferLen; i ++) {
- cipherPos += enc.update(plainText, offset, bufferLen, cipherText, cipherPos);
- offset += bufferLen;
+ //
+ // encryption pass
+ //
+ enc.doFinal(input, encResult);
+ input.flip();
+ encResult.flip();
+ if (!output.equals(encResult)) {
+ byte[] b = new byte[output.remaining()];
+ output.get(b);
+ byte[] c = new byte[encResult.remaining()];
+ encResult.get(c);
+ Assert.fail("AES failed encryption - expected "
+ + new String(DatatypeConverter.printHexBinary(b)) + " got "
+ + new String(DatatypeConverter.printHexBinary(c)));
}
- cipherPos += enc.doFinal(plainText, offset, dataLen % bufferLen, cipherText, cipherPos);
-
- offset = 0;
- // decrypt (update + doFinal) the data
- byte[] realPlainText = new byte[cipherPos + blockSize];
- int plainPos = 0;
- for (int i = 0; i < cipherPos / bufferLen; i ++) {
- plainPos += dec.update(cipherText, offset, bufferLen, realPlainText, plainPos);
- offset += bufferLen;
+
+ //
+ // decryption pass
+ //
+ dec.doFinal(encResult, decResult);
+ decResult.flip();
+
+ if (!input.equals(decResult)) {
+ byte[] inArray = new byte[input.remaining()];
+ byte[] decResultArray = new byte[decResult.remaining()];
+ input.get(inArray);
+ decResult.get(decResultArray);
+ Assert.fail();
}
- plainPos += dec.doFinal(cipherText, offset, cipherPos % bufferLen, realPlainText, plainPos);
+ }
- // verify
- Assert.assertEquals("random byte array length changes after transformation",
- dataLen, plainPos);
+ /** test byte array whose data is planned in {@link TestData} */
+ private void byteArrayTest(CipherTransformation transformation, byte[] key,
+ byte[] iv, byte[] input, byte[] output)
+ throws GeneralSecurityException {
+ resetCipher(transformation, key, iv);
+ int blockSize = transformation.getAlgorithmBlockSize();
+
+ byte[] temp = new byte[input.length + blockSize];
+ int n = enc.doFinal(input, 0, input.length, temp, 0);
+ byte[] cipherText = new byte[n];
+ System.arraycopy(temp, 0, cipherText, 0, n);
+ Assert.assertArrayEquals("byte array encryption error.", output,
+ cipherText);
+
+ temp = new byte[cipherText.length + blockSize];
+ int m = dec.doFinal(cipherText, 0, cipherText.length, temp, 0);
+ byte[] plainText = new byte[m];
+ System.arraycopy(temp, 0, plainText, 0, m);
+ Assert.assertArrayEquals("byte array decryption error.", input,
+ plainText);
+ }
- byte[] shrinkPlainText = new byte[plainPos];
- System.arraycopy(realPlainText, 0, shrinkPlainText, 0, plainPos);
- Assert.assertArrayEquals("random byte array contents changes after transformation",
- plainText, shrinkPlainText);
- }
+ /** test byte array whose data is randomly generated */
+ private void byteArrayTest(CipherTransformation transformation, byte[] key,
+ byte[] iv) throws GeneralSecurityException {
+ int blockSize = transformation.getAlgorithmBlockSize();
+
+ // AES_CBC_NOPADDING only accepts data whose size is the multiple of
+ // block size
+ int[] dataLenList = (transformation == CipherTransformation.AES_CBC_NOPADDING) ? new int[] { 10 * 1024 }
+ : new int[] { 10 * 1024, 10 * 1024 - 3 };
+ for (int dataLen : dataLenList) {
+ byte[] plainText = new byte[dataLen];
+ Random random = new SecureRandom();
+ random.nextBytes(plainText);
+ byte[] cipherText = new byte[dataLen + blockSize];
+
+ // check update method with inputs whose sizes are the multiple of
+ // block size or not
+ int[] bufferLenList = new int[] { 2 * 1024 - 128, 2 * 1024 - 125 };
+ for (int bufferLen : bufferLenList) {
+ resetCipher(transformation, key, iv);
+
+ int offset = 0;
+ // encrypt (update + doFinal) the data
+ int cipherPos = 0;
+ for (int i = 0; i < dataLen / bufferLen; i++) {
+ cipherPos += enc.update(plainText, offset, bufferLen,
+ cipherText, cipherPos);
+ offset += bufferLen;
+ }
+ cipherPos += enc.doFinal(plainText, offset,
+ dataLen % bufferLen, cipherText, cipherPos);
+
+ offset = 0;
+ // decrypt (update + doFinal) the data
+ byte[] realPlainText = new byte[cipherPos + blockSize];
+ int plainPos = 0;
+ for (int i = 0; i < cipherPos / bufferLen; i++) {
+ plainPos += dec.update(cipherText, offset, bufferLen,
+ realPlainText, plainPos);
+ offset += bufferLen;
+ }
+ plainPos += dec.doFinal(cipherText, offset, cipherPos
+ % bufferLen, realPlainText, plainPos);
+
+ // verify
+ Assert.assertEquals(
+ "random byte array length changes after transformation",
+ dataLen, plainPos);
+
+ byte[] shrinkPlainText = new byte[plainPos];
+ System.arraycopy(realPlainText, 0, shrinkPlainText, 0, plainPos);
+ Assert.assertArrayEquals(
+ "random byte array contents changes after transformation",
+ plainText, shrinkPlainText);
+ }
+ }
}
- }
- private void resetCipher(CipherTransformation transformation, byte[] key, byte[] iv) {
- enc = getCipher(transformation);
- dec = getCipher(transformation);
+ private void resetCipher(CipherTransformation transformation, byte[] key,
+ byte[] iv) {
+ enc = getCipher(transformation);
+ dec = getCipher(transformation);
- try {
- enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
- }
+ try {
+ enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
- try {
- dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
- }
- }
-
- private CryptoCipher getCipher(CipherTransformation transformation) {
- try {
- return (CryptoCipher) ReflectionUtils
- .newInstance(ReflectionUtils.getClassByName(cipherClass), props,
- transformation);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
+ try {
+ dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
}
- }
+ private CryptoCipher getCipher(CipherTransformation transformation) {
+ try {
+ return (CryptoCipher) ReflectionUtils.newInstance(
+ ReflectionUtils.getClassByName(cipherClass), props,
+ transformation);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java b/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
index 3653cf9..bc1f6bd 100644
--- a/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
+++ b/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
@@ -26,32 +26,32 @@ import junit.framework.Assert;
import org.junit.Test;
public class CryptoCipherFactoryTest {
- @Test
- public void testDefaultCipher() throws GeneralSecurityException {
- CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
- CipherTransformation.AES_CBC_NOPADDING);
- Assert.assertEquals(OpensslCipher.class.getName(),
- defaultCipher.getClass().getName());
- }
+ @Test
+ public void testDefaultCipher() throws GeneralSecurityException {
+ CryptoCipher defaultCipher = CryptoCipherFactory
+ .getInstance(CipherTransformation.AES_CBC_NOPADDING);
+ Assert.assertEquals(OpensslCipher.class.getName(), defaultCipher
+ .getClass().getName());
+ }
- @Test
- public void testEmptyCipher() throws GeneralSecurityException {
- Properties properties = new Properties();
- properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY, "");
- CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
- CipherTransformation.AES_CBC_NOPADDING, properties);
- Assert.assertEquals(OpensslCipher.class.getName(),
- defaultCipher.getClass().getName());
- }
+ @Test
+ public void testEmptyCipher() throws GeneralSecurityException {
+ Properties properties = new Properties();
+ properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY, "");
+ CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
+ CipherTransformation.AES_CBC_NOPADDING, properties);
+ Assert.assertEquals(OpensslCipher.class.getName(), defaultCipher
+ .getClass().getName());
+ }
- @Test
- public void testInvalidCipher() throws GeneralSecurityException {
- Properties properties = new Properties();
- properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
- "InvalidCipherName");
- CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
- CipherTransformation.AES_CBC_NOPADDING, properties);
- Assert.assertEquals(JceCipher.class.getName(),
- defaultCipher.getClass().getName());
- }
+ @Test
+ public void testInvalidCipher() throws GeneralSecurityException {
+ Properties properties = new Properties();
+ properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
+ "InvalidCipherName");
+ CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
+ CipherTransformation.AES_CBC_NOPADDING, properties);
+ Assert.assertEquals(JceCipher.class.getName(), defaultCipher.getClass()
+ .getName());
+ }
}