From 23448e6aca98618e728f20cda317ea105d684e8b Mon Sep 17 00:00:00 2001 From: Luca Frosini Date: Tue, 5 Feb 2019 11:01:36 +0000 Subject: [PATCH] Improving Common Encryption git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-encryption@176975 82a268e6-3cf1-43bd-a215-b396298e98cf --- .classpath | 38 +---- .project | 11 -- .settings/org.eclipse.jdt.core.prefs | 7 +- distro/INSTALL | 1 - distro/LICENSE | 6 +- distro/MAINTAINERS | 1 - distro/README | 94 +++++++----- distro/changelog.xml | 9 ++ distro/descriptor.xml | 48 ------- distro/profile-template.xml | 23 --- distro/profile.xml | 21 +-- distro/svnpath.txt | 1 - pom.xml | 74 ++-------- .../gcube/common/encryption/IEncrypter.java | 15 +- .../gcube/common/encryption/KeyFactory.java | 11 +- .../common/encryption/KeySerialization.java | 10 +- .../common/encryption/StringEncrypter.java | 89 ++++++++---- .../gcube/common/encryption/SymmetricKey.java | 135 ++++++++---------- .../org/gcube/common/encryption}/KeyTool.java | 28 +++- .../gcube/common/encryption/LocalKeyTest.java | 22 +++ .../encryption/StringEncrypterTest.java | 23 ++- .../common/encryption/SymmetricKeyTest.java | 62 ++++---- 22 files changed, 337 insertions(+), 392 deletions(-) delete mode 100644 distro/INSTALL delete mode 100644 distro/MAINTAINERS delete mode 100644 distro/descriptor.xml delete mode 100644 distro/profile-template.xml delete mode 100644 distro/svnpath.txt rename src/{main/java/org/gcube/common/encryption/keytool => test/java/org/gcube/common/encryption}/KeyTool.java (87%) create mode 100644 src/test/java/org/gcube/common/encryption/LocalKeyTest.java diff --git a/.classpath b/.classpath index e43402f..4d469fb 100644 --- a/.classpath +++ b/.classpath @@ -1,36 +1,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + diff --git a/.project b/.project index 2b495a0..0a65e0b 100644 --- a/.project +++ b/.project @@ -20,15 +20,4 @@ org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature - - - 1454509324033 - - 14 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-target - - - diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 6249222..13b3428 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -1,12 +1,13 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.compliance=1.8 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.7 +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/distro/INSTALL b/distro/INSTALL deleted file mode 100644 index 8d1c8b6..0000000 --- a/distro/INSTALL +++ /dev/null @@ -1 +0,0 @@ - diff --git a/distro/LICENSE b/distro/LICENSE index 630ba97..7bca8c8 100644 --- a/distro/LICENSE +++ b/distro/LICENSE @@ -1,6 +1,2 @@ -gCube System - License ------------------------------------------------------------- +${gcube.license} -The gCube/gCore software is licensed as Free Open Source software conveying to the EUPL (http://ec.europa.eu/idabc/eupl). -The software and documentation is provided by its authors/distributors "as is" and no expressed or -implied warranty is given for its use, quality or fitness for a particular case. diff --git a/distro/MAINTAINERS b/distro/MAINTAINERS deleted file mode 100644 index 7b32448..0000000 --- a/distro/MAINTAINERS +++ /dev/null @@ -1 +0,0 @@ -* Manuele Simi (manuele.simi@isti.cnr.it), CNR, Pisa - Italy \ No newline at end of file diff --git a/distro/README b/distro/README index 5964f42..77f6499 100644 --- a/distro/README +++ b/distro/README @@ -1,38 +1,66 @@ -The gCube System - ${name} ----------------------- - -This work is partially funded by the European Commission in the -context of the iMarine project (www.imarine.eu) - -Authors -------- - -* Manuele Simi (manuele.simi@isti.cnr.it), CNR, Pisa - Italy - -Version and Release Date ------------------------- -${version} - -Description ------------ +The gCube System - ${name} +-------------------------------------------------- + ${description} - + +${gcube.description} + +${gcube.funding} + + +Version +-------------------------------------------------- + +${version} (${buildDate}) + +Please see the file named "changelog.xml" in this directory for the release notes. + + +Authors +-------------------------------------------------- + +* Roberto Cirillo (roberto.cirillo-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy). +* Luca Frosini (luca.frosini-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy). + + +Maintainers +----------- + +* Roberto Cirillo (roberto.cirillo-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy). +* Luca Frosini (luca.frosini-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy). + + Download information --------------------- - -Source code is available from SVN: -${scm.url} - -Binaries can be downloaded from: - - +-------------------------------------------------- + +Source code is available from SVN: + ${scm.url} + +Binaries can be downloaded from the gCube website: + ${gcube.website} + + +Installation +-------------------------------------------------- + +Installation documentation is available on-line in the gCube Wiki: + ${gcube.wikiRoot} + + Documentation -------------- -Documentation is available on-line from the Projects Documentation Wiki: -https://gcube.wiki.gcube-system.org/gcube/index.php/Common-utils-encryption - - +-------------------------------------------------- + +Documentation is available on-line in the gCube Wiki: + ${gcube.wikiRoot} + +Support +-------------------------------------------------- + +Bugs and support requests can be reported in the gCube issue tracking tool: + ${gcube.issueTracking} + + Licensing ---------- - +-------------------------------------------------- + This software is licensed under the terms you may find in the file named "LICENSE" in this directory. diff --git a/distro/changelog.xml b/distro/changelog.xml index 302576a..199d94f 100644 --- a/distro/changelog.xml +++ b/distro/changelog.xml @@ -1,4 +1,13 @@ + + + + SymmetricKey is now a public class + Fixed StringEncrypted decrypt/encrypt signatures. Deprecated olds ones + Added the facility to store a key in a file in KeySerialization class + SymmetricKey is now a public class + Made public the fuctions used to crreates keys in KeyFactory class + Compliancy with the new Maven-based release procedure diff --git a/distro/descriptor.xml b/distro/descriptor.xml deleted file mode 100644 index 4cda8a9..0000000 --- a/distro/descriptor.xml +++ /dev/null @@ -1,48 +0,0 @@ - - servicearchive - - dir - - / - - - ${distroDirectory} - / - true - - README - LICENSE - INSTALL - MAINTAINERS - changelog.xml - - 755 - true - - - target/apidocs - /${artifactId}/doc/api - true - 755 - - - - - ${distroDirectory}/profile.xml - /etc - true - - - target/${build.finalName}.jar - /${artifactId} - - - ${distroDirectory}/svnpath.txt - /${artifactId} - true - - - \ No newline at end of file diff --git a/distro/profile-template.xml b/distro/profile-template.xml deleted file mode 100644 index 6a5364b..0000000 --- a/distro/profile-template.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - Service - - ${description} - Common - ${artifactId} - ${version} - - - ${description} - ${artifactId} - ${version} - - ${build.finalName}.jar - - - - - - - diff --git a/distro/profile.xml b/distro/profile.xml index 993c9ea..c510260 100644 --- a/distro/profile.xml +++ b/distro/profile.xml @@ -1,28 +1,29 @@ - + + Service - A collection of Encryption utilities - Common - common-utils-encryption + ${description} + ${serviceClass} + ${artifactId} 1.0.0 - A collection of Encryption utilities + ${description} ${artifactId} ${version} - org.gcube.common - common-utils-encryption - 1.0.1-SNAPSHOT + ${groupId} + ${artifactId} + ${version} + Library - common-utils-encryption-1.0.1-SNAPSHOT.jar + ${build.finalName}.${project.packaging} - diff --git a/distro/svnpath.txt b/distro/svnpath.txt deleted file mode 100644 index f416f9d..0000000 --- a/distro/svnpath.txt +++ /dev/null @@ -1 +0,0 @@ -${scm.url} diff --git a/pom.xml b/pom.xml index 4e5becd..91f7aed 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 @@ -8,7 +9,7 @@ org.gcube.core common-encryption - 2.0.0-SNAPSHOT + 1.1.0-SNAPSHOT EncryptionLibrary A collection of Encryption utilities @@ -16,82 +17,33 @@ scm:svn:https://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-utils-encryption http://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-utils-encryption - - - - - org.gcube.distribution - gcube-bom - 1.0.0-SNAPSHOT - pom - import - - - - - distro + UTF-8 + ${project.basedir}/distro + Common - - org.gcube.common - authorization-client - - - org.gcube.common - common-authorization - junit junit 4.7 test + + org.gcube.core + common-scope + [1.0.0-SNAPSHOT,2.0.0-SNAPSHOT) + org.apache.maven.plugins maven-assembly-plugin - - - ${distroDirectory}/descriptor.xml - - - servicearchive - install - - single - - - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.5 - - - copy-profile - install - - copy-resources - - - target - - - ${distroDirectory} - true - - profile.xml - - - - + make-servicearchive + package diff --git a/src/main/java/org/gcube/common/encryption/IEncrypter.java b/src/main/java/org/gcube/common/encryption/IEncrypter.java index 0852e3c..14b91b6 100644 --- a/src/main/java/org/gcube/common/encryption/IEncrypter.java +++ b/src/main/java/org/gcube/common/encryption/IEncrypter.java @@ -5,21 +5,31 @@ import java.security.Key; /** * * @author Roberto Cirillo (CNR) - * + * @author Luca Frosini (ISTI - CNR) + * * @param the type of the object to encrypt/decrypt */ public interface IEncrypter { + public T encrypt(T t) throws Exception; + + public T encrypt(T t, Key key) throws Exception; + /** * Encrypts with the given key or the default key * @param t the object to encrypt * @param key the key * @return the encrypted object * @throws Exception if the key is not available, invalid or the object cannot be encrypted - */ + @Deprecated public T encrypt(T t, Key ... key) throws Exception; + + public T decrypt(T t) throws Exception; + + public T decrypt(T t, Key key) throws Exception; + /** * Decrypts with the given key or the default key * @param t the object to decrypt @@ -27,6 +37,7 @@ public interface IEncrypter { * @return the decrypted object * @throws Exception if the key is not available, invalid or the object cannot be decrypted */ + @Deprecated public T decrypt(T t, Key ... key) throws Exception; diff --git a/src/main/java/org/gcube/common/encryption/KeyFactory.java b/src/main/java/org/gcube/common/encryption/KeyFactory.java index b047e4a..a8469c1 100644 --- a/src/main/java/org/gcube/common/encryption/KeyFactory.java +++ b/src/main/java/org/gcube/common/encryption/KeyFactory.java @@ -6,14 +6,15 @@ import javax.crypto.SecretKey; /** * A simplified keys generator for the most common algorithms * @author Manuele Simi (CNR) - * + * @author Roberto Cirillo (ISTI - CNR) + * @author Luca Frosini (ISTI - CNR) */ public class KeyFactory { /** * Generates an AES key */ - protected static SecretKey newAESKey() throws Exception { + public static SecretKey newAESKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); return keyGenerator.generateKey(); @@ -22,7 +23,7 @@ public class KeyFactory { /** * Generates a TripleDES key */ - protected static SecretKey newTripleDESKey() throws Exception { + public static SecretKey newTripleDESKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("TripleDES"); //keyGenerator.init(168); return keyGenerator.generateKey(); @@ -31,7 +32,7 @@ public class KeyFactory { /** * Generates a Rijndael key */ - protected static SecretKey newRijndaelKey() throws Exception { + public static SecretKey newRijndaelKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("Rijndael"); //keyGenerator.init(168); return keyGenerator.generateKey(); @@ -40,7 +41,7 @@ public class KeyFactory { /** * Generates a DESede key */ - protected static SecretKey newDESKey() throws Exception { + public static SecretKey newDESKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); //keyGenerator.init(168); return keyGenerator.generateKey(); diff --git a/src/main/java/org/gcube/common/encryption/KeySerialization.java b/src/main/java/org/gcube/common/encryption/KeySerialization.java index dedceba..eeb93c9 100644 --- a/src/main/java/org/gcube/common/encryption/KeySerialization.java +++ b/src/main/java/org/gcube/common/encryption/KeySerialization.java @@ -13,7 +13,8 @@ import javax.crypto.spec.DESedeKeySpec; /** * Manage keys serialization * @author Manuele Simi (CNR) - * + * @author Roberto Cirillo (ISTI - CNR) + * @author Luca Frosini (ISTI - CNR) */ public class KeySerialization { @@ -23,13 +24,12 @@ public class KeySerialization { * @param file the file where to store the key * @throws Exception */ - protected static void store(Key key, File file) throws Exception { + public static void store(Key key, File file) throws Exception { byte[] keyBytes = key.getEncoded(); FileOutputStream f = new FileOutputStream(file); f.write(keyBytes); f.close(); System.out.println("Key successfully stored in " + file.toURI().toURL().toString()); - } /** @@ -49,8 +49,8 @@ public class KeySerialization { private static byte[] getBytesFromFile(File file) { byte[] data = new byte[(int) file.length()]; - try { - new FileInputStream(file).read(data); + try(FileInputStream ins = new FileInputStream(file)) { + ins.read(data); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/org/gcube/common/encryption/StringEncrypter.java b/src/main/java/org/gcube/common/encryption/StringEncrypter.java index 0f515dd..2b37ae0 100644 --- a/src/main/java/org/gcube/common/encryption/StringEncrypter.java +++ b/src/main/java/org/gcube/common/encryption/StringEncrypter.java @@ -3,38 +3,56 @@ package org.gcube.common.encryption; import javax.crypto.Cipher; import java.security.Key; import javax.xml.bind.DatatypeConverter; + /** * Encrypter for {@link String} objects * @author Manuele Simi (CNR) - * + * @author Roberto Cirillo (ISTI - CNR) + * @author Luca Frosini (ISTI - CNR) */ -public class StringEncrypter implements IEncrypter{ - +public class StringEncrypter implements IEncrypter { + private static StringEncrypter singleton; - - StringEncrypter() {} + + StringEncrypter() { + } /** * Gets the Encrypter for {@link String} * @return the encrypter */ - public static StringEncrypter getEncrypter(){ - if (singleton == null) singleton = new StringEncrypter(); + public static StringEncrypter getEncrypter() { + if(singleton == null) { + singleton = new StringEncrypter(); + } return singleton; } + /** + * Encrypts the string with the context Key + * @param string the string to encrypt + * @return the encrypted string in a Base64 encoding + * @throws Exception + */ + @Override + public String encrypt(String string) throws Exception { + Key ekey = SymmetricKey.getKey(); + return encrypt(string, ekey); + } + /** * Encrypts the string with the given key + * @param string the string to encrypt * @param key the key for encrypting * @return the encrypted string in a Base64 encoding * @throws Exception */ - public String encrypt(String string, Key ... key) throws Exception { - Key ekey = (key!=null && key.length>0)? key[0] : SymmetricKey.getKey(); - Cipher cipher = Cipher.getInstance(ekey.getAlgorithm()); - cipher.init(Cipher.ENCRYPT_MODE, ekey); -// return new String(Base64.encode(cipher.doFinal(string.getBytes()))); - return new String(DatatypeConverter.printBase64Binary((cipher.doFinal(string.getBytes())))); + @Override + public String encrypt(String string, Key ekey) throws Exception { + Cipher cipher = Cipher.getInstance(ekey.getAlgorithm()); + cipher.init(Cipher.ENCRYPT_MODE, ekey); + // return new String(Base64.encode(cipher.doFinal(string.getBytes()))); + return new String(DatatypeConverter.printBase64Binary((cipher.doFinal(string.getBytes())))); } /** @@ -43,35 +61,50 @@ public class StringEncrypter implements IEncrypter{ * @return the encrypted string in a Base64 encoding * @throws Exception */ - public String encrypt(String string, String context) throws Exception { - return encrypt(string, SymmetricKey.getKeyByFile(context)); + @Deprecated + @Override + public String encrypt(String string, Key... key) throws Exception { + Key ekey = (key != null && key.length > 0) ? key[0] : SymmetricKey.getKey(); + return encrypt(string, ekey); } - /** * Decrypts the string with the given key * @param key the key to use for decrypting * @return the decripted string * @throws Exception */ - public String decrypt(String string, Key ... key) throws Exception { - Key dkey = (key!=null && key.length>0)? key[0] : SymmetricKey.getKey(); - Cipher cipher = Cipher.getInstance(dkey.getAlgorithm()); - cipher.init(Cipher.DECRYPT_MODE, dkey); -// return new String(cipher.doFinal(Base64.decode(string.getBytes()))); - return new String(cipher.doFinal(DatatypeConverter.parseBase64Binary(string))); + @Override + public String decrypt(String string) throws Exception { + Key dkey = SymmetricKey.getKey(); + return decrypt(string, dkey); } - + /** * Decrypts the string with the given key - * @param keyFileName the file of the key + * @param key the key to use for decrypting * @return the decripted string - * * @throws Exception + * @throws Exception */ - public String decrypt(String string, String context) throws Exception { - return decrypt(string, SymmetricKey.getKeyByFile(context)); - + @Override + public String decrypt(String string, Key dkey) throws Exception { + Cipher cipher = Cipher.getInstance(dkey.getAlgorithm()); + cipher.init(Cipher.DECRYPT_MODE, dkey); + // return new String(cipher.doFinal(Base64.decode(string.getBytes()))); + return new String(cipher.doFinal(DatatypeConverter.parseBase64Binary(string))); } + /** + * Decrypts the string with the given key + * @param key the key to use for decrypting + * @return the decripted string + * @throws Exception + */ + @Deprecated + @Override + public String decrypt(String string, Key... key) throws Exception { + Key dkey = (key != null && key.length > 0) ? key[0] : SymmetricKey.getKey(); + return decrypt(string, dkey); + } } diff --git a/src/main/java/org/gcube/common/encryption/SymmetricKey.java b/src/main/java/org/gcube/common/encryption/SymmetricKey.java index 4d71425..b40a127 100644 --- a/src/main/java/org/gcube/common/encryption/SymmetricKey.java +++ b/src/main/java/org/gcube/common/encryption/SymmetricKey.java @@ -5,38 +5,33 @@ import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.Key; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import javax.crypto.spec.SecretKeySpec; -import org.gcube.common.authorization.client.exceptions.ObjectNotFound; -import org.gcube.common.authorization.library.AuthorizationEntry; -import org.gcube.common.authorization.library.provider.SecurityTokenProvider; -import org.gcube.common.scope.impl.ContextBean; -import org.gcube.common.scope.impl.ContextBean.Type; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.common.scope.impl.ScopeBean.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import static org.gcube.common.authorization.client.Constants.authorizationService; - -//import org.apache.xml.security.utils.JavaUtils; - - -final class SymmetricKey { - - private static Key key; - +/** + * @author Roberto Cirillo (ISTI - CNR) + * @author Lucio Lelii (ISTI - CNR) + * @author Luca Frosini (ISTI - CNR) + */ +public final class SymmetricKey { + + private static Map keyContextMap = Collections.synchronizedMap(new HashMap()); + private static String keyAlgorithm = "AES"; + private static Logger logger = LoggerFactory.getLogger(SymmetricKey.class); + //private constructor - private SymmetricKey() {} - - - /** - * Gets the key for encryption/decryption - * @return the key - * @throws InvalidKeyException if the key is not available or is invalid - */ - protected static Key getKeyByFile(String context) throws InvalidKeyException { - if (key == null) load(getKeyFileName(context)); - return key; + private SymmetricKey() { } /** @@ -44,76 +39,72 @@ final class SymmetricKey { * @return the key * @throws InvalidKeyException if the key is not available or is invalid */ - @Deprecated - protected static Key getKey() throws InvalidKeyException { - if (key == null) load(); - return key; + protected synchronized static Key getKey() throws InvalidKeyException { + if(!keyContextMap.containsKey(ScopeProvider.instance.get())) + load(ScopeProvider.instance.get()); + return keyContextMap.get(ScopeProvider.instance.get()); } - - /** - * Loads the key from the classpaht - * @throws InvalidKeyException if the key is not available or is invalid - */ - private static void load() throws InvalidKeyException { - String token = SecurityTokenProvider.instance.get(); - AuthorizationEntry entry; - try { - entry = authorizationService().get(token); - load(getKeyFileName(entry.getContext())); - } catch (Exception e) { - throw new InvalidKeyException("Unable to load the Key, token not valid",e); + + public static Key loadKeyFromFile(String keyFileName, String keyAlgorithm) throws InvalidKeyException { + try(InputStream is = SymmetricKey.class.getResourceAsStream("/" + keyFileName)) { + byte[] rawKey = getBytesFromStream(is); + Key key = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); + return key; + } catch(Exception e) { + throw new InvalidKeyException("Unable to load the Key " + keyFileName + " from the classpath"); } - } /** - * Loads the key from the classpaht + * Loads the key from the classpath * @throws InvalidKeyException if the key is not available or is invalid */ - private static void load(final String keyFileName) throws InvalidKeyException { + private static void load(String context) throws InvalidKeyException { byte[] rawKey; + String keyFileName = null; try { - InputStream is =SymmetricKey.class.getResourceAsStream("/"+keyFileName); - rawKey = getBytesFromStream(is); - } catch (Exception e) { - throw new InvalidKeyException("Unable to load the Key "+keyFileName+" from the classpath"); - } - try { - key = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); - }catch (Exception e) { - throw new InvalidKeyException(e); - } + keyFileName = getKeyFileName(context); + InputStream is = SymmetricKey.class.getResourceAsStream("/" + keyFileName); + rawKey = getBytesFromStream(is); + } catch(Exception e) { + logger.error("Unable to load the Key " + keyFileName + " from the classpath"); + throw new InvalidKeyException("Unable to load the Key " + keyFileName + " from the classpath"); + } + try { + Key key = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); + keyContextMap.put(context, key); + } catch(Exception e) { + logger.error("error getting key", e); + throw new InvalidKeyException(); + } } - - + private static byte[] getBytesFromStream(InputStream is) throws IOException { byte[] rawKey; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; - while ((nRead = is.read(data, 0, data.length)) != -1) { - buffer.write(data, 0, nRead); + while((nRead = is.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, nRead); } buffer.flush(); - rawKey= buffer.toByteArray(); + rawKey = buffer.toByteArray(); return rawKey; } - protected static String getKeyFileName(String context) throws InvalidKeyException{ - String keyFile=null; - if(context!=null){ - ContextBean bean = new ContextBean(context); - if(bean.is(Type.VRE)) - bean = bean.enclosingScope(); + protected static String getKeyFileName(String context) throws InvalidKeyException { + String keyFile = null; + if(context != null) { + ScopeBean bean = new ScopeBean(context); + if(bean.is(Type.VRE)) + bean = bean.enclosingScope(); String name = bean.name(); - //build keyfile name with name - keyFile=name+".gcubekey"; - }else{ - throw new InvalidKeyException(" invalid key for context: "+context); + //build keyfile name with name + keyFile = name + ".gcubekey"; + } else { + throw new InvalidKeyException("invalid key for scope: " + context); } return keyFile; } - - } diff --git a/src/main/java/org/gcube/common/encryption/keytool/KeyTool.java b/src/test/java/org/gcube/common/encryption/KeyTool.java similarity index 87% rename from src/main/java/org/gcube/common/encryption/keytool/KeyTool.java rename to src/test/java/org/gcube/common/encryption/KeyTool.java index bd15dbd..1dc866d 100644 --- a/src/main/java/org/gcube/common/encryption/keytool/KeyTool.java +++ b/src/test/java/org/gcube/common/encryption/KeyTool.java @@ -1,7 +1,7 @@ -package org.gcube.common.encryption.keytool; +package org.gcube.common.encryption; -import java.io.FileInputStream; import java.io.IOException; +import java.io.FileInputStream; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; @@ -12,11 +12,12 @@ import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; - import javax.crypto.Cipher; - -@Deprecated +/** + * @author Roberto Cirillo (ISTI - CNR) + * @author Luca Frosini (ISTI - CNR) + */ public class KeyTool { // Keystore settings @@ -74,6 +75,23 @@ public class KeyTool { return result; } + /* + * Get public key from keystore. + * The public key is in the certificate. + */ + public static Key getPublicKey(String keyname, String keystore) + throws IOException, KeyStoreException, NoSuchAlgorithmException, + CertificateException { + + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(new FileInputStream(keystore), KEYSTORE_PASS.toCharArray()); + X509Certificate cert = (X509Certificate) ks.getCertificate(keyname); + + if (cert != null) { + return cert.getPublicKey(); + } + return null; + } /* * Encrypt a message using the public key diff --git a/src/test/java/org/gcube/common/encryption/LocalKeyTest.java b/src/test/java/org/gcube/common/encryption/LocalKeyTest.java new file mode 100644 index 0000000..2179c73 --- /dev/null +++ b/src/test/java/org/gcube/common/encryption/LocalKeyTest.java @@ -0,0 +1,22 @@ +package org.gcube.common.encryption; + +import java.security.InvalidKeyException; + +import org.gcube.common.scope.api.ScopeProvider; +import org.junit.BeforeClass; +import org.junit.Test; + +public class LocalKeyTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + ScopeProvider.instance.set("/gcube/devsec"); + } + + @Test + public void test() throws InvalidKeyException { + String key=SymmetricKey.getKeyFileName(ScopeProvider.instance.get()); + System.out.println("file key found: "+key); + } + +} diff --git a/src/test/java/org/gcube/common/encryption/StringEncrypterTest.java b/src/test/java/org/gcube/common/encryption/StringEncrypterTest.java index fc1665a..31fc4a1 100644 --- a/src/test/java/org/gcube/common/encryption/StringEncrypterTest.java +++ b/src/test/java/org/gcube/common/encryption/StringEncrypterTest.java @@ -1,19 +1,23 @@ package org.gcube.common.encryption; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; +import org.gcube.common.encryption.StringEncrypter; +import org.gcube.common.encryption.SymmetricKey; +import org.gcube.common.scope.api.ScopeProvider; import org.junit.AfterClass; import org.junit.BeforeClass; +import org.junit.Test; public class StringEncrypterTest { static java.security.Key key; static String toEnc = "String to encrypt"; - static String toDec="a7XltR+sRVbF53/iOgwHuw==";//"wW9T5/k5VaLdTdc3WlPbWw=="; static String encString; @BeforeClass public static void setUpBeforeClass() throws Exception { + ScopeProvider.instance.set("/gcube/devsec"); key = SymmetricKey.getKey(); } @@ -21,7 +25,7 @@ public class StringEncrypterTest { public static void tearDownAfterClass() throws Exception { } -// @Test + @Test public final void testEncryptDecrypt() { try { System.out.println("---- STRING ENCRYPTION ----"); @@ -42,16 +46,5 @@ public class StringEncrypterTest { } } -// @Test - public final void testDecrypt(){ - try { - System.out.println("---- STRING DECRYPTION ----"); - System.out.println("String to decrypt " + encString); - System.out.println("Decrypted string " + StringEncrypter.getEncrypter().decrypt(toDec,key)); - } catch (Exception e) { - e.printStackTrace(); - fail("failed to decrypt"); - } - } - + } diff --git a/src/test/java/org/gcube/common/encryption/SymmetricKeyTest.java b/src/test/java/org/gcube/common/encryption/SymmetricKeyTest.java index 35a8674..c5db7c0 100644 --- a/src/test/java/org/gcube/common/encryption/SymmetricKeyTest.java +++ b/src/test/java/org/gcube/common/encryption/SymmetricKeyTest.java @@ -5,19 +5,19 @@ import static org.junit.Assert.fail; import java.security.InvalidKeyException; import java.security.Key; +import org.gcube.common.scope.api.ScopeProvider; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -//import org.apache.xml.security.utils.JavaUtils; public class SymmetricKeyTest { Key key1; Key key2; - + @BeforeClass public static void setUpBeforeClass() throws Exception { - + ScopeProvider.instance.set("/gcube/devsec"); } @AfterClass @@ -37,33 +37,33 @@ public class SymmetricKeyTest { } } - // @Test - // public final void testGetKeyOld() throws InvalidKeyException{ - // String keyAlgorithm = "AES"; - // String localKey = "/symm.key"; - // byte[] rawKey; - // try { - // rawKey = JavaUtils.getBytesFromStream(SymmetricKey.class.getResourceAsStream(localKey)); - // } catch (Exception e) { - // System.out.println("Unable to load the Key from the classpath"); - // e.printStackTrace(); - // throw new InvalidKeyException(); - // } - // try { - // key2 = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); - // }catch (Exception e) { - // e.printStackTrace(); - // throw new InvalidKeyException(); - // } - // System.out.println("key successfully loaded"); - // System.out.println("key " + key2.getEncoded()); - // System.out.println("key algorithm " + key2.getAlgorithm()); - // } - // - // @Test - // public final void compare(){ - // assertEquals(key1, key2); - // } - +// @Test +// public final void testGetKeyOld() throws InvalidKeyException{ +// String keyAlgorithm = "AES"; +// String localKey = "/symm.key"; +// byte[] rawKey; +// try { +// rawKey = JavaUtils.getBytesFromStream(SymmetricKey.class.getResourceAsStream(localKey)); +// } catch (Exception e) { +// System.out.println("Unable to load the Key from the classpath"); +// e.printStackTrace(); +// throw new InvalidKeyException(); +// } +// try { +// key2 = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); +// }catch (Exception e) { +// e.printStackTrace(); +// throw new InvalidKeyException(); +// } +// System.out.println("key successfully loaded"); +// System.out.println("key " + key2.getEncoded()); +// System.out.println("key algorithm " + key2.getAlgorithm()); +// } +// +// @Test +// public final void compare(){ +// assertEquals(key1, key2); +// } + }