From 7e206823de84f6580ac010b8e011aad7f5f6afee Mon Sep 17 00:00:00 2001 From: Roberto Cirillo Date: Thu, 7 Feb 2013 09:15:40 +0000 Subject: [PATCH] first version git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-encryption@68947 82a268e6-3cf1-43bd-a215-b396298e98cf --- .classpath | 10 ++ .project | 23 +++ .settings/org.eclipse.core.resources.prefs | 7 + .settings/org.eclipse.jdt.core.prefs | 13 ++ .settings/org.eclipse.m2e.core.prefs | 5 + distro/INSTALL | 1 + distro/LICENSE | 6 + distro/MAINTAINERS | 1 + distro/README | 38 +++++ distro/changelog.xml | 8 + distro/descriptor.xml | 48 ++++++ distro/profile-template.xml | 23 +++ distro/profile.xml | 33 ++++ distro/svnpath.txt | 1 + pom.xml | 84 ++++++++++ .../common/utils/encryption/Encrypter.java | 33 ++++ .../common/utils/encryption/KeyFactory.java | 56 +++++++ .../utils/encryption/KeySerialization.java | 62 +++++++ .../utils/encryption/StringEncrypter.java | 57 +++++++ .../common/utils/encryption/SymmetricKey.java | 99 +++++++++++ .../utils/encryption/keytool/KeyTool.java | 156 ++++++++++++++++++ .../utils/encryption/KeyFactoryTest.java | 68 ++++++++ .../common/utils/encryption/LocalKeyTest.java | 24 +++ .../utils/encryption/StringEncrypterTest.java | 50 ++++++ .../utils/encryption/SymmetricKeyTest.java | 73 ++++++++ .../utils/encryption/XMLDocumentUtils.java | 87 ++++++++++ target/profile.xml | 33 ++++ 27 files changed, 1099 insertions(+) create mode 100644 .classpath create mode 100644 .project create mode 100644 .settings/org.eclipse.core.resources.prefs create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.m2e.core.prefs create mode 100644 distro/INSTALL create mode 100644 distro/LICENSE create mode 100644 distro/MAINTAINERS create mode 100644 distro/README create mode 100644 distro/changelog.xml create mode 100644 distro/descriptor.xml create mode 100644 distro/profile-template.xml create mode 100644 distro/profile.xml create mode 100644 distro/svnpath.txt create mode 100644 pom.xml create mode 100644 src/main/java/org/gcube/common/utils/encryption/Encrypter.java create mode 100644 src/main/java/org/gcube/common/utils/encryption/KeyFactory.java create mode 100644 src/main/java/org/gcube/common/utils/encryption/KeySerialization.java create mode 100644 src/main/java/org/gcube/common/utils/encryption/StringEncrypter.java create mode 100644 src/main/java/org/gcube/common/utils/encryption/SymmetricKey.java create mode 100644 src/main/java/org/gcube/common/utils/encryption/keytool/KeyTool.java create mode 100644 src/test/java/org/gcube/common/utils/encryption/KeyFactoryTest.java create mode 100644 src/test/java/org/gcube/common/utils/encryption/LocalKeyTest.java create mode 100644 src/test/java/org/gcube/common/utils/encryption/StringEncrypterTest.java create mode 100644 src/test/java/org/gcube/common/utils/encryption/SymmetricKeyTest.java create mode 100644 src/test/java/org/gcube/common/utils/encryption/XMLDocumentUtils.java create mode 100644 target/profile.xml diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..0f53f3e --- /dev/null +++ b/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..0a65e0b --- /dev/null +++ b/.project @@ -0,0 +1,23 @@ + + + common-encryption + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..43516ae --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,7 @@ +#Tue Mar 06 09:17:02 EST 2012 +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding//src/test/resources=UTF-8 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..8e8278c --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,13 @@ +#Tue Mar 06 09:17:02 EST 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +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.6 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..644a9f3 --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,5 @@ +#Fri Jan 13 22:25:00 CET 2012 +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/distro/INSTALL b/distro/INSTALL new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/distro/INSTALL @@ -0,0 +1 @@ + diff --git a/distro/LICENSE b/distro/LICENSE new file mode 100644 index 0000000..630ba97 --- /dev/null +++ b/distro/LICENSE @@ -0,0 +1,6 @@ +gCube System - 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 new file mode 100644 index 0000000..7b32448 --- /dev/null +++ b/distro/MAINTAINERS @@ -0,0 +1 @@ +* Manuele Simi (manuele.simi@isti.cnr.it), CNR, Pisa - Italy \ No newline at end of file diff --git a/distro/README b/distro/README new file mode 100644 index 0000000..5964f42 --- /dev/null +++ b/distro/README @@ -0,0 +1,38 @@ +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} + +Download information +-------------------- + +Source code is available from SVN: +${scm.url} + +Binaries can be downloaded from: + + +Documentation +------------- +Documentation is available on-line from the Projects Documentation Wiki: +https://gcube.wiki.gcube-system.org/gcube/index.php/Common-utils-encryption + + +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 new file mode 100644 index 0000000..658d5a0 --- /dev/null +++ b/distro/changelog.xml @@ -0,0 +1,8 @@ + + + Compliancy with the new Maven-based release procedure + + + First Release + + \ No newline at end of file diff --git a/distro/descriptor.xml b/distro/descriptor.xml new file mode 100644 index 0000000..4cda8a9 --- /dev/null +++ b/distro/descriptor.xml @@ -0,0 +1,48 @@ + + 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 new file mode 100644 index 0000000..6a5364b --- /dev/null +++ b/distro/profile-template.xml @@ -0,0 +1,23 @@ + + + + Service + + ${description} + Common + ${artifactId} + ${version} + + + ${description} + ${artifactId} + ${version} + + ${build.finalName}.jar + + + + + + + diff --git a/distro/profile.xml b/distro/profile.xml new file mode 100644 index 0000000..fa6abdc --- /dev/null +++ b/distro/profile.xml @@ -0,0 +1,33 @@ + + + + Service + + A collection of Encryption utilities + Common + common-utils-encryption + 1.0.1 + + org.gcube.common + common-utils-encryption + 1.0.1-SNAPSHOT + + + + A collection of Encryption utilities + common-utils-encryption + 1.0.1-SNAPSHOT + + org.gcube.common + common-utils-encryption + 1.0.1-SNAPSHOT + + + common-utils-encryption-1.0.1-SNAPSHOT.jar + + + + + + + diff --git a/distro/svnpath.txt b/distro/svnpath.txt new file mode 100644 index 0000000..f416f9d --- /dev/null +++ b/distro/svnpath.txt @@ -0,0 +1 @@ +${scm.url} diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..2d18544 --- /dev/null +++ b/pom.xml @@ -0,0 +1,84 @@ + + 4.0.0 + + maven-parent + org.gcube.tools + 1.0.0 + + org.gcube.core + common-utils-encryption + 1.0.1-SNAPSHOT + EncryptionLibrary + A collection of Encryption utilities + + scm:svn:http://svn.d4science.research-infrastructures.eu/gcube/trunk/Common/common-utils-encryption + 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 + + + distro + + + + junit + junit + 4.7 + test + + + org.gcube.core + common-scope + 1.0.0 + + + + + + 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 + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/common/utils/encryption/Encrypter.java b/src/main/java/org/gcube/common/utils/encryption/Encrypter.java new file mode 100644 index 0000000..3f95269 --- /dev/null +++ b/src/main/java/org/gcube/common/utils/encryption/Encrypter.java @@ -0,0 +1,33 @@ +package org.gcube.common.utils.encryption; + +import java.security.Key; + +/** + * + * @author Manuele Simi (CNR) + * + * @param the type of the object to encrypt/decrypt + */ +public interface Encrypter { + + /** + * 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 + + */ + public T encrypt(T t, Key ... key) throws Exception; + + /** + * Decrypts with the given key or the default key + * @param t the object to decrypt + * @param key the key + * @return the decrypted object + * @throws Exception if the key is not available, invalid or the object cannot be decrypted + */ + public T decrypt(T t, Key ... key) throws Exception; + + +} diff --git a/src/main/java/org/gcube/common/utils/encryption/KeyFactory.java b/src/main/java/org/gcube/common/utils/encryption/KeyFactory.java new file mode 100644 index 0000000..531c7e6 --- /dev/null +++ b/src/main/java/org/gcube/common/utils/encryption/KeyFactory.java @@ -0,0 +1,56 @@ +package org.gcube.common.utils.encryption; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; + +/** + * A simplified keys generator for the most common algorithms + * @author Manuele Simi (CNR) + * + */ +public class KeyFactory { + +// static org.apache.commons.logging.Log log = +// org.apache.commons.logging.LogFactory.getLog( +// KeyFactory.class.getName()); +// +// static { +// org.apache.xml.security.Init.init(); +// } + /** + * Generates an AES key + */ + protected static SecretKey newAESKey() throws Exception { + KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); + keyGenerator.init(128); + return keyGenerator.generateKey(); + } + + /** + * Generates a TripleDES key + */ + protected static SecretKey newTripleDESKey() throws Exception { + KeyGenerator keyGenerator = KeyGenerator.getInstance("TripleDES"); + //keyGenerator.init(168); + return keyGenerator.generateKey(); + } + + /** + * Generates a Rijndael key + */ + protected static SecretKey newRijndaelKey() throws Exception { + KeyGenerator keyGenerator = KeyGenerator.getInstance("Rijndael"); + //keyGenerator.init(168); + return keyGenerator.generateKey(); + } + + /** + * Generates a DESede key + */ + protected 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/utils/encryption/KeySerialization.java b/src/main/java/org/gcube/common/utils/encryption/KeySerialization.java new file mode 100644 index 0000000..5cf3d3e --- /dev/null +++ b/src/main/java/org/gcube/common/utils/encryption/KeySerialization.java @@ -0,0 +1,62 @@ +package org.gcube.common.utils.encryption; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.security.Key; + +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESedeKeySpec; + +//import org.apache.xml.security.utils.JavaUtils; + + +/** + * Manage keys serialization + * @author Manuele Simi (CNR) + * + */ +public class KeySerialization { + + /** + * Stores the key + * @param key the key to store + * @param file the file where to store the key + * @throws Exception + */ + protected 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()); + + } + + /** + * Loads the key + * @param file the name of the file where the key has been stored + * @param jceAlgorithmName the name of the algorithm of the key + */ + protected static SecretKey loadDESede(File file, String jceAlgorithmName) throws Exception { + byte[] data=getBytesFromFile(file); +// DESedeKeySpec keySpec = new DESedeKeySpec(JavaUtils.getBytesFromFile(file.getAbsolutePath())); + DESedeKeySpec keySpec = new DESedeKeySpec(data); + SecretKeyFactory skf = SecretKeyFactory.getInstance(jceAlgorithmName); + SecretKey key = skf.generateSecret(keySpec); + System.out.println("Key successfully loaded from " + file.toURI().toURL().toString()); + return key; + } + + private static byte[] getBytesFromFile(File file) { + byte[] data = new byte[(int) file.length()]; + try { + new FileInputStream(file).read(data); + } catch (Exception e) { + e.printStackTrace(); + } + return data; + } + + } diff --git a/src/main/java/org/gcube/common/utils/encryption/StringEncrypter.java b/src/main/java/org/gcube/common/utils/encryption/StringEncrypter.java new file mode 100644 index 0000000..fc32af9 --- /dev/null +++ b/src/main/java/org/gcube/common/utils/encryption/StringEncrypter.java @@ -0,0 +1,57 @@ +package org.gcube.common.utils.encryption; + +import javax.crypto.Cipher; + +//import org.apache.xml.security.utils.Base64; +//import org.apache.axis.encoding.Base64; +import java.security.Key; +import javax.xml.bind.DatatypeConverter; +/** + * Encrypter for {@link String} objects + * @author Manuele Simi (CNR) + * + */ +public class StringEncrypter implements Encrypter{ + + private static StringEncrypter singleton; + + StringEncrypter() {} + + /** + * Gets the Encrypter for {@link String} + * @return the encrypter + */ + public static StringEncrypter getEncrypter(){ + if (singleton == null) singleton = new StringEncrypter(); + return singleton; + } + + /** + * Encrypts the string with the given key + * @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())))); + } + + /** + * 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))); + } + +} diff --git a/src/main/java/org/gcube/common/utils/encryption/SymmetricKey.java b/src/main/java/org/gcube/common/utils/encryption/SymmetricKey.java new file mode 100644 index 0000000..2c8059b --- /dev/null +++ b/src/main/java/org/gcube/common/utils/encryption/SymmetricKey.java @@ -0,0 +1,99 @@ +package org.gcube.common.utils.encryption; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.InvalidKeyException; +import java.security.Key; + +import javax.crypto.spec.SecretKeySpec; + +//import org.apache.xml.security.utils.JavaUtils; +import javax.xml.bind.DatatypeConverter; + +import org.gcube.common.scope.api.ScopeProvider; + + +final class SymmetricKey { + + private static Key key; + + private static String localKey = "/symm.key"; + + private static String keyAlgorithm = "AES"; + + + //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 getKey() throws InvalidKeyException { + if (key == null) load(); + return key; + } + + /** + * Loads the key from the classpaht + * @throws InvalidKeyException if the key is not available or is invalid + */ + private static void load() throws InvalidKeyException { + byte[] rawKey; + try { + InputStream is =SymmetricKey.class.getResourceAsStream("/"+getLocalKey()); + rawKey = getBytesFromStream(is); + } catch (Exception e) { + System.out.println("Unable to load the Key from the classpath"); + e.printStackTrace(); + throw new InvalidKeyException(); + } + try { + key = new SecretKeySpec(rawKey, 0, rawKey.length, keyAlgorithm); + }catch (Exception e) { + e.printStackTrace(); + 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); + } + buffer.flush(); + rawKey= buffer.toByteArray(); + return rawKey; + } + + protected static String getLocalKey() throws InvalidKeyException{ + // virtual organization + String vo=null; + //file that contains the key + String keyFile=null; + String scope=ScopeProvider.instance.get(); + System.out.println("scope founded "+scope); + if((scope !=null) && (scope.contains("/"))){ + String[] vos=scope.split("/"); + // if the scope is a VO or VRE scope + if((vos != null) && (vos.length > 2)){ + System.out.println(" 0 "+vos[0]+" 1 "+vos[1]+" 2 "+vos[2]); + vo=vos[2]; + if(vo !=null){ + keyFile=vo+".gcubekey"; + } + }else{ + throw new InvalidKeyException(" invalid key for scope: "+scope); + } + }else{ + throw new InvalidKeyException(" invalid key for scope: "+scope); + } + return keyFile; + } + +} diff --git a/src/main/java/org/gcube/common/utils/encryption/keytool/KeyTool.java b/src/main/java/org/gcube/common/utils/encryption/keytool/KeyTool.java new file mode 100644 index 0000000..209d8fc --- /dev/null +++ b/src/main/java/org/gcube/common/utils/encryption/keytool/KeyTool.java @@ -0,0 +1,156 @@ +package org.gcube.common.utils.encryption.keytool; + +import java.io.IOException; +import java.io.FileInputStream; +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; +import javax.crypto.Cipher; + + +@Deprecated +public class KeyTool { + + // Keystore settings + private static final String KEYSTORE = "/home/rcirillo/my.keystore"; + private static final String KEYSTORE_PASS = "mysecret"; + private static final String KEYALIAS = "myalias"; + private static final String KEYPASS = "mysecret"; + + /* + * Convert into hex values + */ + private static String hex(String binStr) { + + String newStr = new String(); + + try { + String hexStr = "0123456789ABCDEF"; + byte [] p = binStr.getBytes(); + for(int k=0; k < p.length; k++ ){ + int j = ( p[k] >> 4 )&0xF; + newStr = newStr + hexStr.charAt( j ); + j = p[k]&0xF; + newStr = newStr + hexStr.charAt( j ) + " "; + } + } catch (Exception e) { + System.out.println("Failed to convert into hex values: " + e); + } + + return newStr; + } + + /* + * Get private key from keystore + */ + private static Key getPrivateKey( String keyname, String password, + String keystore) throws IOException, KeyStoreException, + NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException{ + + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(new FileInputStream(keystore), KEYSTORE_PASS.toCharArray()); + Key result = ks.getKey(keyname, password.toCharArray()); + return result; + } + + /* + * Get certficate from keystore. + */ + private static X509Certificate getCertificate(String keyname, + String keystore) throws IOException, KeyStoreException, + NoSuchAlgorithmException, CertificateException { + + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(new FileInputStream(keystore), KEYSTORE_PASS.toCharArray()); + X509Certificate result = (X509Certificate) ks.getCertificate(keyname); + return result; + } + + /* + * Get public key from keystore. + * The public key is in the certificate. + */ + private 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 + * Decrypt the encrypted message using the private key. + */ + public static void main(String [] args){ + + String message = ""; + byte[] messageBytes; + byte [] tempPub = null; + String sPub = null; + byte[] ciphertextBytes = null; + byte[] textBytes = null; + + try { + + // The source of randomness + SecureRandom secureRandom = new SecureRandom(); + + // Obtain a RSA Cipher Object + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding","BC"); + + // Loading certficate from keystore + X509Certificate keystorecert = getCertificate(KEYALIAS, KEYSTORE); + + // Read the public key from keystore certificate + RSAPublicKey keystorepub = (RSAPublicKey) keystorecert.getPublicKey(); + tempPub = keystorepub.getEncoded(); + sPub = new String( tempPub ); + System.out.println("Public key from keystore:\n" + hex(sPub) + "\n"); + + // Read the pivate key from keystore certificate + PrivateKey keystorepriv = (PrivateKey)getPrivateKey(KEYALIAS, KEYPASS, KEYSTORE); + + // Set plain message + message = "This is my secret message."; + messageBytes = message.getBytes(); + System.out.println("Plain message:\n" + message + "\n" ); + + // Initialize the cipher for encryption + cipher.init(Cipher.ENCRYPT_MODE, keystorepub, secureRandom); + + // Encrypt the message + ciphertextBytes = cipher.doFinal(messageBytes); + System.out.println("Message encrypted with keystore public key:\n" + new String(ciphertextBytes) + "\n"); + + // Initialize the cipher for decryption + cipher.init(Cipher.DECRYPT_MODE, keystorepriv, secureRandom); + + // Encrypt the message + textBytes = cipher.doFinal(ciphertextBytes); + System.out.println("Message decrypted with keystore private key:\n" + new String(textBytes) + "\n"); + + }catch( IOException e ){ + System.out.println( "IOException:" + e ); + }catch( CertificateException e ){ + System.out.println( "CertificateException:" + e ); + }catch( NoSuchAlgorithmException e ){ + System.out.println( "NoSuchAlgorithmException:" + e ); + } catch (Exception e) { + System.out.println( "Exception:" + e ); + } + } +} \ No newline at end of file diff --git a/src/test/java/org/gcube/common/utils/encryption/KeyFactoryTest.java b/src/test/java/org/gcube/common/utils/encryption/KeyFactoryTest.java new file mode 100644 index 0000000..6df3fb5 --- /dev/null +++ b/src/test/java/org/gcube/common/utils/encryption/KeyFactoryTest.java @@ -0,0 +1,68 @@ +package org.gcube.common.utils.encryption; + +import static org.junit.Assert.*; + + + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Tester for {@link KeyFactory} + * @author manuele + * + */ +public class KeyFactoryTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Test + public final void testNewAESKey() { + try { + KeyFactory.newAESKey(); + //KeySerialization.store(key, new File("/Users/manuele/work/workspace-gcf/tests/EncryptionWithSantuario/src/main/resources/symm.xml")); + } catch (Exception e) { + fail(""); + e.printStackTrace(); + } + } + + @Test + public final void testNewTripleDESKey() { + try { + KeyFactory.newTripleDESKey(); + } catch (Exception e) { + fail(""); + e.printStackTrace(); + } + } + + @Test + public final void testNewRijndaelKey() { + try { + KeyFactory.newRijndaelKey(); + } catch (Exception e) { + fail(""); + e.printStackTrace(); + } + } + + @Test + public final void testNewDESKey() { + try { + KeyFactory.newDESKey(); + } catch (Exception e) { + fail(""); + e.printStackTrace(); + } + } + + +} diff --git a/src/test/java/org/gcube/common/utils/encryption/LocalKeyTest.java b/src/test/java/org/gcube/common/utils/encryption/LocalKeyTest.java new file mode 100644 index 0000000..3594e15 --- /dev/null +++ b/src/test/java/org/gcube/common/utils/encryption/LocalKeyTest.java @@ -0,0 +1,24 @@ +package org.gcube.common.utils.encryption; + +import static org.junit.Assert.*; + +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.getLocalKey(); + System.out.println("file key founded: "+key); + } + +} diff --git a/src/test/java/org/gcube/common/utils/encryption/StringEncrypterTest.java b/src/test/java/org/gcube/common/utils/encryption/StringEncrypterTest.java new file mode 100644 index 0000000..6cb29d3 --- /dev/null +++ b/src/test/java/org/gcube/common/utils/encryption/StringEncrypterTest.java @@ -0,0 +1,50 @@ +package org.gcube.common.utils.encryption; + +import static org.junit.Assert.*; + +import org.gcube.common.utils.encryption.StringEncrypter; +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 encString; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + key = SymmetricKey.getKey(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Test + public final void testEncrypt() { + try { + System.out.println("---- STRING ENCRYPTION ----"); + System.out.println("String to encrypt " + toEnc); + encString = StringEncrypter.getEncrypter().encrypt(toEnc,key); + System.out.println("Encrypted string " + encString); + } catch (Exception e) { + e.printStackTrace(); + fail("failed to encrypt"); + } + } + + @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(encString,key)); + } catch (Exception e) { + e.printStackTrace(); + fail("failed to decrypt"); + } + } + +} diff --git a/src/test/java/org/gcube/common/utils/encryption/SymmetricKeyTest.java b/src/test/java/org/gcube/common/utils/encryption/SymmetricKeyTest.java new file mode 100644 index 0000000..fe514e5 --- /dev/null +++ b/src/test/java/org/gcube/common/utils/encryption/SymmetricKeyTest.java @@ -0,0 +1,73 @@ +package org.gcube.common.utils.encryption; + +import static org.junit.Assert.*; + +import java.io.InputStream; +import java.security.InvalidKeyException; +import java.security.Key; + +import javax.crypto.spec.SecretKeySpec; + +//import org.apache.xml.security.utils.JavaUtils; +import org.gcube.common.scope.api.ScopeProvider; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class SymmetricKeyTest { + + Key key1; + Key key2; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + ScopeProvider.instance.set("/gcube/devsec"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Test + public final void testGetKey() { + try { + key1= SymmetricKey.getKey(); + System.out.println("key successfully loaded"); + System.out.println("key " + key1.getEncoded()); + System.out.println("key algorithm " + key1.getAlgorithm()); + } catch (InvalidKeyException e) { + e.printStackTrace(); + fail("Failed to load the symmetric key"); + } + } + +// @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); +// } + + +} diff --git a/src/test/java/org/gcube/common/utils/encryption/XMLDocumentUtils.java b/src/test/java/org/gcube/common/utils/encryption/XMLDocumentUtils.java new file mode 100644 index 0000000..a1ba18a --- /dev/null +++ b/src/test/java/org/gcube/common/utils/encryption/XMLDocumentUtils.java @@ -0,0 +1,87 @@ +package org.gcube.common.utils.encryption; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +/** + * Various helpers for XML document serialization + * @author Manuele Simi (CNR) + * + */ +public class XMLDocumentUtils { + /** + * Loads a document from the given file + * @param fileName the absolute path of the file + * @return the document + * @throws Exception if the deserialization fails or the document is not well-formed + */ + protected static Document loadFromFile(String fileName) throws Exception { + File encryptionFile = new File(fileName); + javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(encryptionFile); + System.out.println("Encryption document loaded from " + + encryptionFile.toURI().toURL().toString()); + return document; + } + + /** + * Serializes the document to the given file + * @param doc the document to serialize + * @param fileName the file in which the document is persisted + * @throws Exception if the serialization fails or the document is not well-formed + */ + protected static void sendToFile(Document doc, String fileName) throws Exception { + File encryptionFile = new File(fileName); + FileOutputStream f = new FileOutputStream(encryptionFile); + TransformerFactory factory = TransformerFactory.newInstance(); + Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + DOMSource source = new DOMSource(doc); + StreamResult result = new StreamResult(f); + transformer.transform(source, result); + f.close(); + System.out.println("Wrote document containing encrypted data to " + + encryptionFile.toURI().toURL().toString()); + } + + /** + * Generates a string serialization of the document + * @param doc the document to serialize + * @return the serialized string + * @throws Exception if the serialization fails or the document is not well-formed + */ + public static String serialize(Document doc) throws Exception { + StringWriter stw = new StringWriter(); + Transformer serializer = TransformerFactory.newInstance().newTransformer(); + serializer.transform(new DOMSource(doc), new StreamResult(stw)); + return stw.toString(); + } + + /** + * Loads a document from its string serialization + * @param serializeddoc + * @return + * @throws Exception if the deserialization fails or the document is not well-formed + */ + public static Document deserialize(String serializeddoc) throws Exception{ + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + return builder.parse(new InputSource(new StringReader(serializeddoc))); + } + +} diff --git a/target/profile.xml b/target/profile.xml new file mode 100644 index 0000000..fa6abdc --- /dev/null +++ b/target/profile.xml @@ -0,0 +1,33 @@ + + + + Service + + A collection of Encryption utilities + Common + common-utils-encryption + 1.0.1 + + org.gcube.common + common-utils-encryption + 1.0.1-SNAPSHOT + + + + A collection of Encryption utilities + common-utils-encryption + 1.0.1-SNAPSHOT + + org.gcube.common + common-utils-encryption + 1.0.1-SNAPSHOT + + + common-utils-encryption-1.0.1-SNAPSHOT.jar + + + + + + +