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

View File

@ -20,15 +20,4 @@
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature> <nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures> </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> </projectDescription>

View File

@ -1,12 +1,13 @@
eclipse.preferences.version=1 eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 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.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.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 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} 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
-----------
${description} ${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 Download information
-------------------- --------------------------------------------------
Source code is available from SVN: Source code is available from SVN:
${scm.url} ${scm.url}
Binaries can be downloaded from: 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
------------- --------------------------------------------------
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 Licensing
--------- --------------------------------------------------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory. 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> <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"> <Changeset component="common-encryption.1-0-1" date="04-05-2012">
<Change>Compliancy with the new Maven-based release procedure</Change> <Change>Compliancy with the new Maven-based release procedure</Change>
</Changeset> </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"?> <?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <!DOCTYPE xml>
<Resource>
<ID /> <ID />
<Type>Service</Type> <Type>Service</Type>
<Profile> <Profile>
<Description>A collection of Encryption utilities</Description> <Description>${description}</Description>
<Class>Common</Class> <Class>${serviceClass}</Class>
<Name>common-utils-encryption</Name> <Name>${artifactId}</Name>
<Version>1.0.0</Version> <Version>1.0.0</Version>
<Packages> <Packages>
<Software> <Software>
<Description>A collection of Encryption utilities</Description> <Description>${description}</Description>
<Name>${artifactId}</Name> <Name>${artifactId}</Name>
<Version>${version}</Version> <Version>${version}</Version>
<MavenCoordinates> <MavenCoordinates>
<groupId>org.gcube.common</groupId> <groupId>${groupId}</groupId>
<artifactId>common-utils-encryption</artifactId> <artifactId>${artifactId}</artifactId>
<version>1.0.1-SNAPSHOT</version> <version>${version}</version>
</MavenCoordinates> </MavenCoordinates>
<Type>Library</Type>
<Files> <Files>
<File>common-utils-encryption-1.0.1-SNAPSHOT.jar</File> <File>${build.finalName}.${project.packaging}</File>
</Files> </Files>
</Software> </Software>
</Packages> </Packages>
</Profile> </Profile>
</Resource> </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"> 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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
@ -8,7 +9,7 @@
</parent> </parent>
<groupId>org.gcube.core</groupId> <groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId> <artifactId>common-encryption</artifactId>
<version>2.0.0-SNAPSHOT</version> <version>1.1.0-SNAPSHOT</version>
<name>EncryptionLibrary</name> <name>EncryptionLibrary</name>
<description>A collection of Encryption utilities</description> <description>A collection of Encryption utilities</description>
<scm> <scm>
@ -16,82 +17,33 @@
<developerConnection>scm:svn:https://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-utils-encryption</developerConnection> <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> <url>http://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-utils-encryption</url>
</scm> </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> <properties>
<distroDirectory>distro</distroDirectory> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<distroDirectory>${project.basedir}/distro</distroDirectory>
<serviceClass>Common</serviceClass>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.7</version> <version>4.7</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope</artifactId>
<version>[1.0.0-SNAPSHOT,2.0.0-SNAPSHOT)</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions> <executions>
<execution> <execution>
<id>servicearchive</id> <id>make-servicearchive</id>
<phase>install</phase> <phase>package</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>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>

View File

@ -5,21 +5,31 @@ import java.security.Key;
/** /**
* *
* @author Roberto Cirillo (CNR) * @author Roberto Cirillo (CNR)
* * @author Luca Frosini (ISTI - CNR)
*
* @param <T> the type of the object to encrypt/decrypt * @param <T> the type of the object to encrypt/decrypt
*/ */
public interface IEncrypter<T> { 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 * Encrypts <T> with the given key or the default key
* @param t the object to encrypt * @param t the object to encrypt
* @param key the key * @param key the key
* @return the encrypted object * @return the encrypted object
* @throws Exception if the key is not available, invalid or the object cannot be encrypted * @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 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 * Decrypts <T> with the given key or the default key
* @param t the object to decrypt * @param t the object to decrypt
@ -27,6 +37,7 @@ public interface IEncrypter<T> {
* @return the decrypted object * @return the decrypted object
* @throws Exception if the key is not available, invalid or the object cannot be decrypted * @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; 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 * A simplified keys generator for the most common algorithms
* @author Manuele Simi (CNR) * @author Manuele Simi (CNR)
* * @author Roberto Cirillo (ISTI - CNR)
* @author Luca Frosini (ISTI - CNR)
*/ */
public class KeyFactory { public class KeyFactory {
/** /**
* Generates an AES key * Generates an AES key
*/ */
protected static SecretKey newAESKey() throws Exception { public static SecretKey newAESKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); keyGenerator.init(128);
return keyGenerator.generateKey(); return keyGenerator.generateKey();
@ -22,7 +23,7 @@ public class KeyFactory {
/** /**
* Generates a TripleDES key * Generates a TripleDES key
*/ */
protected static SecretKey newTripleDESKey() throws Exception { public static SecretKey newTripleDESKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("TripleDES"); KeyGenerator keyGenerator = KeyGenerator.getInstance("TripleDES");
//keyGenerator.init(168); //keyGenerator.init(168);
return keyGenerator.generateKey(); return keyGenerator.generateKey();
@ -31,7 +32,7 @@ public class KeyFactory {
/** /**
* Generates a Rijndael key * Generates a Rijndael key
*/ */
protected static SecretKey newRijndaelKey() throws Exception { public static SecretKey newRijndaelKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("Rijndael"); KeyGenerator keyGenerator = KeyGenerator.getInstance("Rijndael");
//keyGenerator.init(168); //keyGenerator.init(168);
return keyGenerator.generateKey(); return keyGenerator.generateKey();
@ -40,7 +41,7 @@ public class KeyFactory {
/** /**
* Generates a DESede key * Generates a DESede key
*/ */
protected static SecretKey newDESKey() throws Exception { public static SecretKey newDESKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
//keyGenerator.init(168); //keyGenerator.init(168);
return keyGenerator.generateKey(); return keyGenerator.generateKey();

View File

@ -13,7 +13,8 @@ import javax.crypto.spec.DESedeKeySpec;
/** /**
* Manage keys serialization * Manage keys serialization
* @author Manuele Simi (CNR) * @author Manuele Simi (CNR)
* * @author Roberto Cirillo (ISTI - CNR)
* @author Luca Frosini (ISTI - CNR)
*/ */
public class KeySerialization { public class KeySerialization {
@ -23,13 +24,12 @@ public class KeySerialization {
* @param file the file where to store the key * @param file the file where to store the key
* @throws Exception * @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(); byte[] keyBytes = key.getEncoded();
FileOutputStream f = new FileOutputStream(file); FileOutputStream f = new FileOutputStream(file);
f.write(keyBytes); f.write(keyBytes);
f.close(); f.close();
System.out.println("Key successfully stored in " + file.toURI().toURL().toString()); System.out.println("Key successfully stored in " + file.toURI().toURL().toString());
} }
/** /**
@ -49,8 +49,8 @@ public class KeySerialization {
private static byte[] getBytesFromFile(File file) { private static byte[] getBytesFromFile(File file) {
byte[] data = new byte[(int) file.length()]; byte[] data = new byte[(int) file.length()];
try { try(FileInputStream ins = new FileInputStream(file)) {
new FileInputStream(file).read(data); ins.read(data);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -3,38 +3,56 @@ package org.gcube.common.encryption;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import java.security.Key; import java.security.Key;
import javax.xml.bind.DatatypeConverter; import javax.xml.bind.DatatypeConverter;
/** /**
* Encrypter for {@link String} objects * Encrypter for {@link String} objects
* @author Manuele Simi (CNR) * @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; private static StringEncrypter singleton;
StringEncrypter() {} StringEncrypter() {
}
/** /**
* Gets the Encrypter for {@link String} * Gets the Encrypter for {@link String}
* @return the encrypter * @return the encrypter
*/ */
public static StringEncrypter getEncrypter(){ public static StringEncrypter getEncrypter() {
if (singleton == null) singleton = new StringEncrypter(); if(singleton == null) {
singleton = new StringEncrypter();
}
return singleton; 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 * Encrypts the string with the given key
* @param string the string to encrypt
* @param key the key for encrypting * @param key the key for encrypting
* @return the encrypted string in a Base64 encoding * @return the encrypted string in a Base64 encoding
* @throws Exception * @throws Exception
*/ */
public String encrypt(String string, Key ... key) throws Exception { @Override
Key ekey = (key!=null && key.length>0)? key[0] : SymmetricKey.getKey(); public String encrypt(String string, Key ekey) throws Exception {
Cipher cipher = Cipher.getInstance(ekey.getAlgorithm()); Cipher cipher = Cipher.getInstance(ekey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, ekey); cipher.init(Cipher.ENCRYPT_MODE, ekey);
// return new String(Base64.encode(cipher.doFinal(string.getBytes()))); // return new String(Base64.encode(cipher.doFinal(string.getBytes())));
return new String(DatatypeConverter.printBase64Binary((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 * @return the encrypted string in a Base64 encoding
* @throws Exception * @throws Exception
*/ */
public String encrypt(String string, String context) throws Exception { @Deprecated
return encrypt(string, SymmetricKey.getKeyByFile(context)); @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 * Decrypts the string with the given key
* @param key the key to use for decrypting * @param key the key to use for decrypting
* @return the decripted string * @return the decripted string
* @throws Exception * @throws Exception
*/ */
public String decrypt(String string, Key ... key) throws Exception { @Override
Key dkey = (key!=null && key.length>0)? key[0] : SymmetricKey.getKey(); public String decrypt(String string) throws Exception {
Cipher cipher = Cipher.getInstance(dkey.getAlgorithm()); Key dkey = SymmetricKey.getKey();
cipher.init(Cipher.DECRYPT_MODE, dkey); return decrypt(string, 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 * 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 * @return the decripted string
* * @throws Exception * @throws Exception
*/ */
public String decrypt(String string, String context) throws Exception { @Override
return decrypt(string, SymmetricKey.getKeyByFile(context)); 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.io.InputStream;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.Key; import java.security.Key;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.authorization.library.AuthorizationEntry; import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.scope.impl.ScopeBean.Type;
import org.gcube.common.scope.impl.ContextBean; import org.slf4j.Logger;
import org.gcube.common.scope.impl.ContextBean.Type; import org.slf4j.LoggerFactory;
import static org.gcube.common.authorization.client.Constants.authorizationService; /**
* @author Roberto Cirillo (ISTI - CNR)
//import org.apache.xml.security.utils.JavaUtils; * @author Lucio Lelii (ISTI - CNR)
* @author Luca Frosini (ISTI - CNR)
*/
final class SymmetricKey { public final class SymmetricKey {
private static Key key; private static Map<String,Key> keyContextMap = Collections.synchronizedMap(new HashMap<String,Key>());
private static String keyAlgorithm = "AES"; private static String keyAlgorithm = "AES";
private static Logger logger = LoggerFactory.getLogger(SymmetricKey.class);
//private constructor //private constructor
private SymmetricKey() {} 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;
} }
/** /**
@ -44,76 +39,72 @@ final class SymmetricKey {
* @return the key * @return the key
* @throws InvalidKeyException if the key is not available or is invalid * @throws InvalidKeyException if the key is not available or is invalid
*/ */
@Deprecated protected synchronized static Key getKey() throws InvalidKeyException {
protected static Key getKey() throws InvalidKeyException { if(!keyContextMap.containsKey(ScopeProvider.instance.get()))
if (key == null) load(); load(ScopeProvider.instance.get());
return key; return keyContextMap.get(ScopeProvider.instance.get());
} }
/** public static Key loadKeyFromFile(String keyFileName, String keyAlgorithm) throws InvalidKeyException {
* Loads the key from the classpaht try(InputStream is = SymmetricKey.class.getResourceAsStream("/" + keyFileName)) {
* @throws InvalidKeyException if the key is not available or is invalid byte[] rawKey = getBytesFromStream(is);
*/ Key key = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm);
private static void load() throws InvalidKeyException { return key;
String token = SecurityTokenProvider.instance.get(); } catch(Exception e) {
AuthorizationEntry entry; throw new InvalidKeyException("Unable to load the Key " + keyFileName + " from the classpath");
try {
entry = authorizationService().get(token);
load(getKeyFileName(entry.getContext()));
} catch (Exception e) {
throw new InvalidKeyException("Unable to load the Key, token not valid",e);
} }
} }
/** /**
* Loads the key from the classpaht * Loads the key from the classpath
* @throws InvalidKeyException if the key is not available or is invalid * @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; byte[] rawKey;
String keyFileName = null;
try { try {
InputStream is =SymmetricKey.class.getResourceAsStream("/"+keyFileName); keyFileName = getKeyFileName(context);
rawKey = getBytesFromStream(is); InputStream is = SymmetricKey.class.getResourceAsStream("/" + keyFileName);
} catch (Exception e) { rawKey = getBytesFromStream(is);
throw new InvalidKeyException("Unable to load the Key "+keyFileName+" from the classpath"); } catch(Exception e) {
} logger.error("Unable to load the Key " + keyFileName + " from the classpath");
try { throw new InvalidKeyException("Unable to load the Key " + keyFileName + " from the classpath");
key = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); }
}catch (Exception e) { try {
throw new InvalidKeyException(e); 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 { private static byte[] getBytesFromStream(InputStream is) throws IOException {
byte[] rawKey; byte[] rawKey;
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead; int nRead;
byte[] data = new byte[16384]; byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) { while((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead); buffer.write(data, 0, nRead);
} }
buffer.flush(); buffer.flush();
rawKey= buffer.toByteArray(); rawKey = buffer.toByteArray();
return rawKey; return rawKey;
} }
protected static String getKeyFileName(String context) throws InvalidKeyException{ protected static String getKeyFileName(String context) throws InvalidKeyException {
String keyFile=null; String keyFile = null;
if(context!=null){ if(context != null) {
ContextBean bean = new ContextBean(context); ScopeBean bean = new ScopeBean(context);
if(bean.is(Type.VRE)) if(bean.is(Type.VRE))
bean = bean.enclosingScope(); bean = bean.enclosingScope();
String name = bean.name(); String name = bean.name();
//build keyfile name with name //build keyfile name with name
keyFile=name+".gcubekey"; keyFile = name + ".gcubekey";
}else{ } else {
throw new InvalidKeyException(" invalid key for context: "+context); throw new InvalidKeyException("invalid key for scope: " + context);
} }
return keyFile; 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.IOException;
import java.io.FileInputStream;
import java.security.Key; import java.security.Key;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.KeyStoreException; import java.security.KeyStoreException;
@ -12,11 +12,12 @@ import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey; import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher; import javax.crypto.Cipher;
/**
@Deprecated * @author Roberto Cirillo (ISTI - CNR)
* @author Luca Frosini (ISTI - CNR)
*/
public class KeyTool { public class KeyTool {
// Keystore settings // Keystore settings
@ -74,6 +75,23 @@ public class KeyTool {
return result; 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 * 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; 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.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test;
public class StringEncrypterTest { public class StringEncrypterTest {
static java.security.Key key; static java.security.Key key;
static String toEnc = "String to encrypt"; static String toEnc = "String to encrypt";
static String toDec="a7XltR+sRVbF53/iOgwHuw==";//"wW9T5/k5VaLdTdc3WlPbWw==";
static String encString; static String encString;
@BeforeClass @BeforeClass
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
ScopeProvider.instance.set("/gcube/devsec");
key = SymmetricKey.getKey(); key = SymmetricKey.getKey();
} }
@ -21,7 +25,7 @@ public class StringEncrypterTest {
public static void tearDownAfterClass() throws Exception { public static void tearDownAfterClass() throws Exception {
} }
// @Test @Test
public final void testEncryptDecrypt() { public final void testEncryptDecrypt() {
try { try {
System.out.println("---- STRING ENCRYPTION ----"); 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.InvalidKeyException;
import java.security.Key; import java.security.Key;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
//import org.apache.xml.security.utils.JavaUtils;
public class SymmetricKeyTest { public class SymmetricKeyTest {
Key key1; Key key1;
Key key2; Key key2;
@BeforeClass @BeforeClass
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
ScopeProvider.instance.set("/gcube/devsec");
} }
@AfterClass @AfterClass
@ -37,33 +37,33 @@ public class SymmetricKeyTest {
} }
} }
// @Test // @Test
// public final void testGetKeyOld() throws InvalidKeyException{ // public final void testGetKeyOld() throws InvalidKeyException{
// String keyAlgorithm = "AES"; // String keyAlgorithm = "AES";
// String localKey = "/symm.key"; // String localKey = "/symm.key";
// byte[] rawKey; // byte[] rawKey;
// try { // try {
// rawKey = JavaUtils.getBytesFromStream(SymmetricKey.class.getResourceAsStream(localKey)); // rawKey = JavaUtils.getBytesFromStream(SymmetricKey.class.getResourceAsStream(localKey));
// } catch (Exception e) { // } catch (Exception e) {
// System.out.println("Unable to load the Key from the classpath"); // System.out.println("Unable to load the Key from the classpath");
// e.printStackTrace(); // e.printStackTrace();
// throw new InvalidKeyException(); // throw new InvalidKeyException();
// } // }
// try { // try {
// key2 = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); // key2 = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm);
// }catch (Exception e) { // }catch (Exception e) {
// e.printStackTrace(); // e.printStackTrace();
// throw new InvalidKeyException(); // throw new InvalidKeyException();
// } // }
// System.out.println("key successfully loaded"); // System.out.println("key successfully loaded");
// System.out.println("key " + key2.getEncoded()); // System.out.println("key " + key2.getEncoded());
// System.out.println("key algorithm " + key2.getAlgorithm()); // System.out.println("key algorithm " + key2.getAlgorithm());
// } // }
// //
// @Test // @Test
// public final void compare(){ // public final void compare(){
// assertEquals(key1, key2); // assertEquals(key1, key2);
// } // }
} }