diff options
author | Magdalena GrodziĆska <mag.grodzinska@gmail.com> | 2020-01-14 22:53:45 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-01-14 22:53:45 +0100 |
commit | 47ff68f0535f90eb4b09cb8c9c88555abd900cc8 (patch) | |
tree | 4ed4b28dc3d97a74646c977c4efbf6471e7f6f67 /src/main/java/pl/edu/mimuw/cloudatlas/querysigner | |
parent | 50924560e8829914a4b8d315752c693890210c88 (diff) | |
parent | 42abac9eda30ba47ef6e710d0af22969f657a0cd (diff) |
Merge pull request #118 from m-chrzan/query_signer
Query signer
Diffstat (limited to 'src/main/java/pl/edu/mimuw/cloudatlas/querysigner')
5 files changed, 291 insertions, 0 deletions
diff --git a/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/KeyUtils.java b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/KeyUtils.java new file mode 100644 index 0000000..7a543ba --- /dev/null +++ b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/KeyUtils.java @@ -0,0 +1,35 @@ +package pl.edu.mimuw.cloudatlas.querysigner; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.*; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +public class KeyUtils { + private final static String ENCRYPTION_ALGORITHM = "RSA"; + + public static PublicKey getPublicKey(String filename){ + try { + byte[] byteKey = Files.readAllBytes(Paths.get(filename)); + X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey); + KeyFactory kf = KeyFactory.getInstance(ENCRYPTION_ALGORITHM); + return kf.generatePublic(X509publicKey); + } catch(Exception e) { + e.printStackTrace(); + } + return null; + } + + public static PrivateKey getPrivateKey(String filename){ + try { + byte[] byteKey = Files.readAllBytes(Paths.get(filename)); + PKCS8EncodedKeySpec PKCS8privateKey = new PKCS8EncodedKeySpec(byteKey); + KeyFactory kf = KeyFactory.getInstance(ENCRYPTION_ALGORITHM); + return kf.generatePrivate(PKCS8privateKey); + } catch(Exception e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QueryData.java b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QueryData.java new file mode 100644 index 0000000..a9e039e --- /dev/null +++ b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QueryData.java @@ -0,0 +1,44 @@ +package pl.edu.mimuw.cloudatlas.querysigner; + +import java.io.Serializable; + +public class QueryData implements Serializable { + // Original source code + private String code; + // Query signature + private byte[] signature; + // Query signing timestamp + private long timestamp; + + private boolean installed; + + public QueryData(String code, byte[] signature) { + this.code = code; + this.signature = signature; + this.timestamp = System.currentTimeMillis(); + this.installed = true; + } + + public QueryData(String code, byte[] signature, long timestamp, boolean installed) { + this.code = code; + this.signature = signature; + this.timestamp = timestamp; + this.installed = installed; + } + + public String getCode() { + return code; + } + + public byte[] getSignature() { + return signature; + } + + public long getTimestamp() { + return timestamp; + } + + public boolean isInstalled() { return installed; } + + public void setInstalled(boolean installed) { this.installed = installed; } +} diff --git a/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QuerySigner.java b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QuerySigner.java new file mode 100644 index 0000000..b2f426e --- /dev/null +++ b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QuerySigner.java @@ -0,0 +1,44 @@ +package pl.edu.mimuw.cloudatlas.querysigner; + +import pl.edu.mimuw.cloudatlas.querysignerapi.QuerySignerApi; + +import java.io.IOException; +import java.rmi.registry.LocateRegistry; +import java.rmi.registry.Registry; +import java.rmi.server.UnicastRemoteObject; +import java.security.PrivateKey; +import java.security.PublicKey; + +public class QuerySigner { + public static class InvalidQueryException extends Exception { + InvalidQueryException() { + super("Query invalid"); + } + } + + public static QuerySignerApiImplementation initApi() throws IOException { + String publicKeyFile = System.getProperty("public_key_file"); + String privateKeyFile = System.getProperty("private_key_file"); + PublicKey publicKey = KeyUtils.getPublicKey(publicKeyFile); + PrivateKey privateKey = KeyUtils.getPrivateKey(privateKeyFile); + return new QuerySignerApiImplementation(publicKey, privateKey); + } + + public static void runRegistry() { + try { + QuerySignerApiImplementation api = initApi(); + QuerySignerApi apiStub = + (QuerySignerApi) UnicastRemoteObject.exportObject(api, 0); + Registry registry = LocateRegistry.getRegistry(); + registry.rebind("QuerySignerApi", apiStub); + System.out.println("QuerySigner: api bound"); + } catch (Exception e) { + System.err.println("QuerySigner registry initialization exception:"); + e.printStackTrace(); + } + } + + public static void main(String[] args) { + runRegistry(); + } +} diff --git a/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QuerySignerApiImplementation.java b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QuerySignerApiImplementation.java new file mode 100644 index 0000000..a6233d3 --- /dev/null +++ b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QuerySignerApiImplementation.java @@ -0,0 +1,141 @@ +package pl.edu.mimuw.cloudatlas.querysigner; + +import pl.edu.mimuw.cloudatlas.ByteSerializer; +import pl.edu.mimuw.cloudatlas.querysignerapi.QuerySignerApi; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import java.rmi.RemoteException; +import java.security.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class QuerySignerApiImplementation implements QuerySignerApi { + private final static String ENCRYPTION_ALGORITHM = "RSA"; + private final static String DIGEST_ALGORITHM = "SHA-256"; + private PublicKey publicKey; + private PrivateKey privateKey; + private Map<String, QueryData> queries; + private Set<String> attribsSetByQueries; + + public QuerySignerApiImplementation(PublicKey publicKey, PrivateKey privateKey) { + this.publicKey = publicKey; + this.privateKey = privateKey; + this.queries = new HashMap<>(); + this.attribsSetByQueries = new HashSet<>(); + } + + private static String byteArrayToString(byte[] arr, int offset, int len) { + StringBuffer sb = new StringBuffer(); + for (int i = offset, n = Math.min(arr.length, offset + len); i < n; ++i) { + String hex = Integer.toHexString(0xFF & arr[i]); + if (hex.length() < 2) { + sb.append('0'); + } + sb.append(hex); + } + return sb.toString(); + } + + private byte[] encryptQuery(byte[] query) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { + Cipher signCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); + signCipher.init(Cipher.ENCRYPT_MODE, privateKey); + byte[] encryptedBytes = signCipher.doFinal(query); + System.out.println( + "Bytes encrypted with " + ENCRYPTION_ALGORITHM + + ": " + byteArrayToString( + encryptedBytes, 0, encryptedBytes.length)); + return encryptedBytes; + } + + private static byte[] decryptQuery(byte[] encryptedQuery, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException { + Cipher verifyCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); + verifyCipher.init(Cipher.DECRYPT_MODE, publicKey); + byte[] decryptedBytes = verifyCipher.doFinal(encryptedQuery); + System.out.println( + "Bytes decrypted with " + ENCRYPTION_ALGORITHM + + ": " + byteArrayToString( + decryptedBytes, 0, decryptedBytes.length)); + return decryptedBytes; + } + + private static byte[] cryptographicHash(byte[] serializedQuery) throws NoSuchAlgorithmException { + MessageDigest digestGenerator = + MessageDigest.getInstance(DIGEST_ALGORITHM); + byte[] digest = digestGenerator.digest(serializedQuery); + System.out.println( + DIGEST_ALGORITHM + " digest: " + + byteArrayToString( + digest, 0, digest.length)); + return digest; + } + + private static byte[] serializeQuery(String queryName, String queryCode, Boolean install) { + ByteSerializer byteSerializer = new ByteSerializer(); + if (install) { + return byteSerializer.serialize(queryName + queryCode + install.toString()); + } else { + return byteSerializer.serialize(queryName + install.toString()); + } + } + + private QueryData signQuery(String queryName, String queryCode, Boolean install) throws RemoteException { + QueryUtils.validateQueryName(queryName); + try { + byte[] serializedQuery = serializeQuery(queryName, queryCode, install); + byte[] hashedQuery = cryptographicHash(serializedQuery); + byte[] querySignature = encryptQuery(hashedQuery); + QueryData newQuery = new QueryData(queryCode, querySignature); + newQuery.setInstalled(install); + this.queries.put(queryName, newQuery); + return newQuery; + } catch (Exception e) { + e.printStackTrace(); + throw new RemoteException(e.getLocalizedMessage()); + } + } + + @Override + public QueryData signInstallQuery(String queryName, String queryCode) throws RemoteException { + QueryUtils.validateQueryName(queryName); + if (this.queries.containsKey(queryName) && this.queries.get(queryName).isInstalled()) { + throw new RemoteException("Query already installed"); + } else { + return signQuery(queryName, queryCode, true); + } + } + + public static void validateInstallQuery(String queryName, QueryData query, PublicKey publicKey) throws RemoteException,IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, QuerySigner.InvalidQueryException { + validateQuery(queryName, query, publicKey, true); + } + + public static void validateQuery(String queryName, QueryData query, PublicKey publicKey, boolean install) throws RemoteException,IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, QuerySigner.InvalidQueryException { + QueryUtils.validateQueryName(queryName); + byte[] decryptedQuery = decryptQuery(query.getSignature(), publicKey); + byte[] serializedQuery = serializeQuery(queryName, query.getCode(), install); + byte[] hashedSerializedQuery = cryptographicHash(serializedQuery); + String decryptedQueryString = byteArrayToString(decryptedQuery, 0, decryptedQuery.length); + String hashedSerializedQueryString = byteArrayToString(hashedSerializedQuery, 0, hashedSerializedQuery.length); + if (!decryptedQueryString.equals(hashedSerializedQueryString)) { + throw new QuerySigner.InvalidQueryException(); + } + } + + @Override + public QueryData signUninstallQuery(String queryName) throws RemoteException { + QueryUtils.validateQueryName(queryName); + if (this.queries.containsKey(queryName) && this.queries.get(queryName).isInstalled()) { + return signQuery(queryName, "", false); + } else { + throw new RemoteException("Query is not installed"); + } + } + + public static void validateUninstallQuery(String queryName, QueryData query, PublicKey publicKey) throws RemoteException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, QuerySigner.InvalidQueryException, NoSuchPaddingException, InvalidKeyException { + validateQuery(queryName, query, publicKey, false); + } +} diff --git a/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QueryUtils.java b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QueryUtils.java new file mode 100644 index 0000000..c46e32d --- /dev/null +++ b/src/main/java/pl/edu/mimuw/cloudatlas/querysigner/QueryUtils.java @@ -0,0 +1,27 @@ +package pl.edu.mimuw.cloudatlas.querysigner; + +import pl.edu.mimuw.cloudatlas.model.ValueQuery; + +import java.rmi.RemoteException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class QueryUtils { + + public static void validateQueryName(String queryName) throws RemoteException { + Pattern queryNamePattern = Pattern.compile("&[a-zA-Z][\\w_]*"); + Matcher matcher = queryNamePattern.matcher(queryName); + if (!matcher.matches()) { + throw new RemoteException("Invalid query identifier"); + } + } + + public static QueryData constructQueryData(ValueQuery valueQuery) { + return new QueryData( + valueQuery.getCode(), + valueQuery.getSignature(), + valueQuery.getTimestamp(), + valueQuery.isInstalled() + ); + } +} |