Improving Common Encryption

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-encryption@176975 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2019-02-05 11:01:36 +00:00
parent 4880954689
commit 23448e6aca
22 changed files with 337 additions and 392 deletions

View File

@ -1,36 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/classes" path="src/main/java"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -20,15 +20,4 @@
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
<filteredResources>
<filter>
<id>1454509324033</id>
<name></name>
<type>14</type>
<matcher>
<id>org.eclipse.ui.ide.multiFilter</id>
<arguments>1.0-name-matches-false-false-target</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View File

@ -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

View File

@ -1 +0,0 @@

View File

@ -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.

View File

@ -1 +0,0 @@
* Manuele Simi (manuele.simi@isti.cnr.it), CNR, Pisa - Italy

View File

@ -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.

View File

@ -1,4 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<ReleaseNotes>
<Changeset component="common-encryption.1-1-0" date="${buildDate}">
<Change>SymmetricKey is now a public class</Change>
<Change>Fixed StringEncrypted decrypt/encrypt signatures. Deprecated olds ones</Change>
<Change>Added the facility to store a key in a file in KeySerialization class</Change>
<Change>SymmetricKey is now a public class</Change>
<Change>Made public the fuctions used to crreates keys in KeyFactory class</Change>
</Changeset>
<Changeset component="common-encryption.1-0-1" date="04-05-2012">
<Change>Compliancy with the new Maven-based release procedure</Change>
</Changeset>

View File

@ -1,48 +0,0 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>dir</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>INSTALL</include>
<include>MAINTAINERS</include>
<include>changelog.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
<fileSet>
<directory>target/apidocs</directory>
<outputDirectory>/${artifactId}/doc/api</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<fileMode>755</fileMode>
</fileSet>
</fileSets>
<files>
<file>
<source>${distroDirectory}/profile.xml</source>
<outputDirectory>/etc</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>target/${build.finalName}.jar</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
<file>
<source>${distroDirectory}/svnpath.txt</source>
<outputDirectory>/${artifactId}</outputDirectory>
<filtered>true</filtered>
</file>
</files>
</assembly>

View File

@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID />
<Type>Service</Type>
<Profile>
<Description>${description}</Description>
<Class>Common</Class>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<Packages>
<Software>
<Description>${description}</Description>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<Files>
<File>${build.finalName}.jar</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

View File

@ -1,28 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!DOCTYPE xml>
<Resource>
<ID />
<Type>Service</Type>
<Profile>
<Description>A collection of Encryption utilities</Description>
<Class>Common</Class>
<Name>common-utils-encryption</Name>
<Description>${description}</Description>
<Class>${serviceClass}</Class>
<Name>${artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Description>A collection of Encryption utilities</Description>
<Description>${description}</Description>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>org.gcube.common</groupId>
<artifactId>common-utils-encryption</artifactId>
<version>1.0.1-SNAPSHOT</version>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Type>Library</Type>
<Files>
<File>common-utils-encryption-1.0.1-SNAPSHOT.jar</File>
<File>${build.finalName}.${project.packaging}</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

View File

@ -1 +0,0 @@
${scm.url}

74
pom.xml
View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@ -8,7 +9,7 @@
</parent>
<groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId>
<version>2.0.0-SNAPSHOT</version>
<version>1.1.0-SNAPSHOT</version>
<name>EncryptionLibrary</name>
<description>A collection of Encryption utilities</description>
<scm>
@ -16,82 +17,33 @@
<developerConnection>scm:svn:https://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-utils-encryption</developerConnection>
<url>http://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-utils-encryption</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-bom</artifactId>
<version>1.0.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<distroDirectory>distro</distroDirectory>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<distroDirectory>${project.basedir}/distro</distroDirectory>
<serviceClass>Common</serviceClass>
</properties>
<dependencies>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope</artifactId>
<version>[1.0.0-SNAPSHOT,2.0.0-SNAPSHOT)</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-profile</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<filtering>true</filtering>
<includes>
<include>profile.xml</include>
</includes>
</resource>
</resources>
</configuration>
<id>make-servicearchive</id>
<phase>package</phase>
</execution>
</executions>
</plugin>

View File

@ -5,21 +5,31 @@ import java.security.Key;
/**
*
* @author Roberto Cirillo (CNR)
*
* @author Luca Frosini (ISTI - CNR)
*
* @param <T> the type of the object to encrypt/decrypt
*/
public interface IEncrypter<T> {
public T encrypt(T t) throws Exception;
public T encrypt(T t, Key key) throws Exception;
/**
* Encrypts <T> 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 <T> with the given key or the default key
* @param t the object to decrypt
@ -27,6 +37,7 @@ public interface IEncrypter<T> {
* @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;

View File

@ -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();

View File

@ -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();
}

View File

@ -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<String>{
public class StringEncrypter implements IEncrypter<String> {
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<String>{
* @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);
}
}

View File

@ -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<String,Key> keyContextMap = Collections.synchronizedMap(new HashMap<String,Key>());
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;
}
}

View File

@ -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

View File

@ -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);
}
}

View File

@ -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");
}
}
}

View File

@ -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);
// }
}