diff options
Diffstat (limited to 'vid/src/main/java/org/openecomp/vid/encryption')
3 files changed, 953 insertions, 0 deletions
diff --git a/vid/src/main/java/org/openecomp/vid/encryption/EncryptConvertor.java b/vid/src/main/java/org/openecomp/vid/encryption/EncryptConvertor.java new file mode 100644 index 000000000..51a5ee2e3 --- /dev/null +++ b/vid/src/main/java/org/openecomp/vid/encryption/EncryptConvertor.java @@ -0,0 +1,261 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.encryption; + +import java.lang.Character; + +/** + * The Class EncryptConvertor. + */ +public class EncryptConvertor { + + /** The Constant HEX_CHARS. */ + private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); + + /** + * toHexString(String) - convert a string into its hex equivalent. + * + * @param buf the buf + * @return the string + */ + public final static String toHexString(String buf) { + if (buf == null) return ""; + return toHexString(buf.getBytes()); + } + + /** + * toHexString(byte[]) - convert a byte-string into its hex equivalent. + * + * @param buf the buf + * @return the string + */ + public final static String toHexString(byte[] buf) { + + if (buf == null) return ""; + char[] chars = new char[2 * buf.length]; + for (int i = 0; i < buf.length; ++i) { + chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4]; + chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F]; + } + return new String(chars); + } + + // alternate implementation that's slightly slower +// protected static final byte[] Hexhars = { +// '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' +// }; +// public static String encode(byte[] b) { +// StringBuilder s = new StringBuilder(2 * b.length); +// for (int i = 0; i < b.length; i++) { +// int v = b[i] & 0xff; +// s.append((char)Hexhars[v >> 4]); +// s.append((char)Hexhars[v & 0xf]); +// } +// return s.toString(); +// } + + /** + * Convert a hex string to its equivalent value. + * + * @param hexString the hex string + * @return the string + * @throws Exception the exception + */ + public final static String stringFromHex(String hexString) throws Exception + { + if (hexString == null) return ""; + return stringFromHex(hexString.toCharArray()); + } + + /** + * String from hex. + * + * @param hexCharArray the hex char array + * @return the string + * @throws Exception the exception + */ + public final static String stringFromHex(char[] hexCharArray) + throws Exception { + if (hexCharArray == null) return ""; + return new String(bytesFromHex(hexCharArray)); + } + + /** + * Bytes from hex. + * + * @param hexString the hex string + * @return the byte[] + * @throws Exception the exception + */ + public final static byte[] bytesFromHex(String hexString) throws Exception + { + if (hexString == null) return new byte[0]; + return bytesFromHex(hexString.toCharArray()); + } + + /** + * Bytes from hex. + * + * @param hexCharArray the hex char array + * @return the byte[] + * @throws Exception the exception + */ + public final static byte[] bytesFromHex(char[] hexCharArray) + throws Exception { + if (hexCharArray == null) return new byte[0]; + int len = hexCharArray.length; + if ((len % 2) != 0) throw new Exception("Odd number of characters: '" + String.valueOf(hexCharArray) + "'"); + byte [] txtInByte = new byte [len / 2]; + int j = 0; + for (int i = 0; i < len; i += 2) { + txtInByte[j++] = (byte)(((fromHexDigit(hexCharArray[i], i) << 4) | fromHexDigit(hexCharArray[i+1], i)) & 0xFF); + } + return txtInByte; + } + + /** + * From hex digit. + * + * @param ch the ch + * @param index the index + * @return the int + * @throws Exception the exception + */ + protected final static int fromHexDigit(char ch, int index) throws Exception + { + int digit = Character.digit(ch, 16); + if (digit == -1) throw new Exception("Illegal hex character '" + ch + "' at index " + index); + return digit; + } + + // UNIT TESTS (same junit, but we want to run from command line + + /** + * Check to hex string B. + * + * @param arg the arg + * @param expected the expected + * @return true, if successful + */ + public static boolean checkToHexStringB(String arg, String expected) { + String ret = toHexString(arg != null ? arg.getBytes() : null); + System.out.println("toHexString(" + arg + ")=> " + ret); + if (!ret.equals(expected)) System.out.println("\tWRONG, expected: " + expected); + return ret.equals(expected); + } + + /** + * Check to hex string. + * + * @param arg the arg + * @param expected the expected + * @return true, if successful + */ + public static boolean checkToHexString(String arg, String expected) { + String ret = toHexString(arg); + System.out.println("toHexString(" + arg + ")=> " + ret); + if (!ret.equals(expected)) System.out.println("\tWRONG, expected: " + expected); + return ret.equals(expected); + } + + /** + * Check from hex string. + * + * @param arg the arg + * @param expected the expected + * @return true, if successful + */ + public static boolean checkFromHexString(String arg, String expected) { + try { + String ret = stringFromHex(arg); + System.out.println("fromHexString(" + arg + ")=> " + ret); + if (!ret.equals(expected)) System.out.println("\tWRONG, expected: " + expected); + return ret.equals(expected); + } catch (Exception e) { + System.out.println("Caught exception: " + e.toString()); + return false; + } + } + + /** + * Check from hex string B. + * + * @param arg the arg + * @param expected the expected + * @return true, if successful + */ + public static boolean checkFromHexStringB(String arg, String expected) { + try { + byte[] ret = bytesFromHex(arg); + String sret = new String(ret); + System.out.println("fromHexString(" + arg + ")=> " + sret); + if (!sret.equals(expected)) System.out.println("\tWRONG, expected: " + expected); + return sret.equals(expected); + } catch (Exception e) { + System.out.println("Caught exception: " + e.toString()); + return false; + } + } + + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + int pass = 0, fail = 0; + if (checkToHexString("", "")) pass++; else fail++; + if (checkToHexString(null, "")) pass++; else fail++; + if (checkToHexString("0", "30")) pass++; else fail++; + if (checkToHexString("abc", "616263")) pass++; else fail++; + if (checkToHexString("!@#$%^&*()", "21402324255e262a2829")) pass++; else fail++; + if (checkToHexStringB("", "")) pass++; else fail++; + if (checkToHexStringB(null, "")) pass++; else fail++; + if (checkToHexStringB("0", "30")) pass++; else fail++; + if (checkToHexStringB("abc", "616263")) pass++; else fail++; + if (checkToHexStringB("!@#$%^&*()", "21402324255e262a2829")) pass++; else fail++; + if (checkFromHexString("", "")) pass++; else fail++; + if (checkFromHexString(null, "")) pass++; else fail++; + if (checkFromHexString("30", "0")) pass++; else fail++; + if (checkFromHexString("616263", "abc")) pass++; else fail++; + if (checkFromHexString("21402324255e262a2829", "!@#$%^&*()")) pass++; else fail++; + if (checkFromHexStringB("", "")) pass++; else fail++; + if (checkFromHexStringB(null, "")) pass++; else fail++; + if (checkFromHexStringB("30", "0")) pass++; else fail++; + if (checkFromHexStringB("616263", "abc")) pass++; else fail++; + if (checkFromHexStringB("21402324255e262a2829", "!@#$%^&*()")) pass++; else fail++; + System.out.println("Tests passed: " + Integer.toString(pass)); + System.out.println("Tests failed: " + Integer.toString(fail)); + System.out.println("======="); + System.out.println("abc toHex = " + toHexString("abc")); + System.out.println("123 toHex = " + toHexString("123")); + try { + System.out.println("616263 FromHex = " + stringFromHex("616263")); + System.out.println("313233 FromHex = " + stringFromHex("313233")); + //System.out.println("current key FromHex = " + stringFromHex("57ajqe{kJjjarj}G#(3)ea7")); + } catch (Exception e) { + System.out.println("exception: " + e.toString()); + } + } + +} diff --git a/vid/src/main/java/org/openecomp/vid/encryption/EncryptedConfiguration.java b/vid/src/main/java/org/openecomp/vid/encryption/EncryptedConfiguration.java new file mode 100644 index 000000000..30d40812d --- /dev/null +++ b/vid/src/main/java/org/openecomp/vid/encryption/EncryptedConfiguration.java @@ -0,0 +1,413 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.encryption; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.util.Properties; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + + +/** + * Class to manage encrypted configuration values. + */ +public class EncryptedConfiguration { + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EncryptedConfiguration.class); + + + /** Our secret key and method. */ + private String encryptionKey; + + /** The encryption method. */ + private String encryptionMethod; + + /** + * Where to log when things go wrong. + * + * @param key the key + * @param method the method + */ + + public EncryptedConfiguration(String key, String method) { + encryptionKey = key.trim(); + encryptionMethod = method; + } + + /** + * Retrieve an encrypted string from the given configuration. + * The name will have ".x" appended to it. + * Decoded from hex, it will be "method:hexsalt:hexvalue". + * The format of the value will be in hex. + * Method will be "r" to begin with, for "rc4". + * + * @param f the f + * @param name the name + * @param deflt the deflt + * @return the string + * @throws Exception the exception + */ + public String getString(String f, String name, String deflt) + throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "==> getString"); + return getString(f, name, deflt, encryptionKey); + } + + /** + * Retrieve an encrypted string from the given configuration. + * The name will have ".x" appended to it. + * Decoded from hex, it will be "method:hexsalt:hexvalue". + * The format of the value will be in hex. + * Method will be "r" to begin with, for "rc4". + * + * @param f the f + * @param name the name + * @param deflt the deflt + * @param key the key + * @return the string + * @throws Exception the exception + */ + public String getString(String f, String name, String deflt, String key) + throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "==> getString"); + logger.debug(EELFLoggerDelegate.debugLogger, " key = " + key); + Properties prop = new Properties(); + InputStream input = null; + + try { + input = new FileInputStream(f); + + prop.load(input); + + /* for testing, a dump of all key-value pairs + Enumeration<?> e = prop.propertyNames(); + while (e.hasMoreElements()) { + String k = (String) e.nextElement(); + String value = prop.getProperty(k); + System.out.println("Key : " + k + ", Value : " + value); + } + */ + + } catch (IOException ex) { + ex.printStackTrace(); // TODO: fix + } finally { + input.close(); + } + + String str = prop.getProperty(name + ".x"); + logger.debug(EELFLoggerDelegate.debugLogger, "str = " + str); + + if (str == null) { + // not encrypted version + str = prop.getProperty(name); + if (str == null) { + return deflt; + } + return str; + } + + String method = encryptionMethod; + logger.debug(EELFLoggerDelegate.debugLogger, "method = " + method); + String salt = EncryptedConfiguration.generateSalt(); + logger.debug(EELFLoggerDelegate.debugLogger, "salt = " + salt); + + return decrypt(str, key, method, salt); + } + + /** + * Decrypt a string in 'method:hexsalt:hexvalue' format. + * + * @param triple the triple + * @param key the key + * @param method the method + * @param salt the salt + * @return the string + * @throws Exception the exception + */ + public static String decrypt(String triple, String key, String method, String salt) throws Exception { + /* + String[] strParts = triple.trim().split(":"); + if (strParts.length != 3) throw new Exception("Encrypted value must look like 'x:y:z'"); + return decrypt(strParts[0], Convert.stringFromHex(strParts[1]), key, Convert.bytesFromHex(strParts[2])); + */ + + return decrypt(method, salt, key, EncryptConvertor.bytesFromHex(triple)); + } + + /** + * Decrypt a string 'method:hexsalt:hexvalue' format. + * + * @param method the method + * @param salt the salt + * @param key the key + * @param bvalue the bvalue + * @return the string + * @throws Exception the exception + */ + public static String decrypt(String method, String salt, String key, byte[] bvalue) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "==> decrypt method"); + logger.debug(EELFLoggerDelegate.debugLogger, " method = " + method); + logger.debug(EELFLoggerDelegate.debugLogger, " salt = " + salt); + logger.debug(EELFLoggerDelegate.debugLogger, " key = " + key); + byte[] secretKey = runDigest(salt + "." + key); + + SecretKeySpec skeySpec = new SecretKeySpec(secretKey, method); + + Cipher cipher = Cipher.getInstance(method); // "AES" + cipher.init(Cipher.DECRYPT_MODE, skeySpec); + + byte[] decrypted = cipher.doFinal(bvalue); + return new String(decrypted); + } + + /** + * Encrypt a string using the given method, salt and key. + * + * @param method the method + * @param salt the salt + * @param key the key + * @param value the value + * @return the byte[] + * @throws Exception the exception + */ + public static byte[] encrypt(String method, String salt, String key, String value) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "==> encrypt() method"); + byte[] bvalue = value.getBytes(); + byte[] secretKey = runDigest(salt + "." + key); + + SecretKeySpec skeySpec = new SecretKeySpec(secretKey, method); + + Cipher cipher = Cipher.getInstance(method); // "AES" + cipher.init(Cipher.ENCRYPT_MODE, skeySpec); + + byte[] encrypted = cipher.doFinal(bvalue); + return encrypted; + } + + /** + * Prepare a secret key by running a digest on it. + * + * @param text the text + * @return the byte[] + * @throws Exception the exception + */ + private static byte[] runDigest(String text) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "==> runDigest() method"); + MessageDigest md = MessageDigest.getInstance("MD5"); + md.reset(); + md.update(text.getBytes(), 0, text.length()); + return md.digest(); + } + + /** + * Encrypt a string using the given method, salt and key, and return it as a hex-formated triple. + * + * @param method the method + * @param salt the salt + * @param key the key + * @param value the value + * @return the string + * @throws Exception the exception + */ + public static String encryptToTriple(String method, String salt, String key, String value) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "==> Enter encryptToTriple()"); + logger.debug(EELFLoggerDelegate.debugLogger, "method = " + method); + logger.debug(EELFLoggerDelegate.debugLogger, "salt = " + salt); + logger.debug(EELFLoggerDelegate.debugLogger, "key = " + key); + logger.debug(EELFLoggerDelegate.debugLogger, "valye = " + value); + + /* + StringBuffer sb = new StringBuffer(method); + sb.append(":").append(Convert.toHexString(salt)) + .append(":").append(Convert.toHexString(encrypt(method, salt, key, value))); + logger.debug("s = " + sb.toString()); + */ + + StringBuffer sb2 = new StringBuffer(""); + sb2.append(EncryptConvertor.toHexString(encrypt(method, salt, key, value))); + String s = sb2.toString(); + logger.debug(EELFLoggerDelegate.debugLogger, "s = " + s); + return s; + } + + /** + * Create a value that can be used as a salt. + * + * @return the string + */ + public static String generateSalt() { + logger.debug(EELFLoggerDelegate.debugLogger, "==> generaltSalt"); + + // G2 wants to hard code the value for salt. + // set the value as 123456789 + // return Long.toString(System.currentTimeMillis() % 1000) + Pid.getPidStr(); + return Long.toString(123456789 % 10000); + } + + /** + * Usage. + */ + public static void usage() { + usage(null); + } + + /** + * Usage. + * + * @param msg the msg + */ + public static void usage(String msg) { + if (msg != null) System.out.println(msg); + System.out.println("Usage: java EncryptedConfiguration -D triple -k key\n" + + "java EncryptedConfiguration -d string -m method [-s salt | -S] -k key\n" + + "java EncryptedConfiguration -e string -m method [-s salt | -S] -k key\n" + + "-D\tdecrypt x:y:z triple\n" + + "-d\tdecrypt string (in hex)\n" + + "-e\tencrypt string\n" + + "-S\tgenerate a salt\n" + ); + System.exit(1); + } + + + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + + Options options = new Options(); + options.addOption("s", true, "salt"); + options.addOption("S", false, "Generate salt"); + options.addOption("k", true, "key"); + options.addOption("m", true, "method"); + options.addOption("e", true, "encryptString"); + options.addOption("d", true, "decryptString"); + options.addOption("D", true, "triple x:y:z"); + options.addOption("h", false, "show help"); + options.addOption("?", false, "show help"); + + String salt = null, key = null, method = null, encStr = null, decStr = null, triple = null; + boolean genSalt = false; + + CommandLineParser parser = new DefaultParser(); + CommandLine cmd = null; + + try { + cmd = parser.parse(options, args); + + System.out.println("You picked " + cmd.toString() + "\n"); + if (cmd.hasOption("s")) { + salt = cmd.getOptionValue("s"); + } + if (cmd.hasOption("S")) { + genSalt = true; + System.out.println("here in S"); + } + if (cmd.hasOption("k")) { + key = cmd.getOptionValue("k"); + } + if (cmd.hasOption("m")) { + method = cmd.getOptionValue("m"); + } + if (cmd.hasOption("e")) { + encStr = cmd.getOptionValue("e"); + } + if (cmd.hasOption("d")) { + decStr = cmd.getOptionValue("d"); + } + if (cmd.hasOption("D")) { + triple = cmd.getOptionValue("D"); + } + if (cmd.hasOption("?") || cmd.hasOption("h")) { + usage(); + System.exit(0); + } + + if (triple == null) { + if ((salt == null) && !genSalt) usage("one of -s or -S must be specified"); + if ((salt != null) && genSalt) usage("only one of -s or -S must be specified"); + if (key == null) usage("-k must be specified"); + if (method == null) usage("-m must be specified"); + if ((encStr == null) && (decStr == null)) usage("one of -d or -e must be specified"); + if ((encStr != null) && (decStr != null)) usage("only one of -d or -e may be specified"); + if (genSalt) { + salt = generateSalt(); + System.out.println("salt = " + salt); + } + + if (encStr != null) + System.out.println(encryptToTriple(method, salt, key, encStr)); + if (decStr != null) + System.out.println(decrypt(method, salt, key, EncryptConvertor.bytesFromHex(decStr))); + } else { + if (key == null) { + usage("-k not specified"); + System.exit(0); + } + System.out.println(decrypt(triple, key, method, salt)); + } + + } catch (ParseException e) { + System.out.println("Failed to parse command line properties e="+e.toString()); + } catch (Exception e) { + System.out.println("Failed to run EncryptedConfiguration main() e="+e.toString()); + } + + // http://forums.sun.com/thread.jspa?threadID=5290983 + // try { + // String message = "Strong Versus Unlimited Strength Cryptography"; + // SecretKeySpec skeySpec = new SecretKeySpec("0123456789ABCDEF".getBytes(), "AES"); //AES-128 + + // Cipher cipher = Cipher.getInstance("AES"); // "AES/ECB/NoPadding" + // cipher.init(Cipher.ENCRYPT_MODE, skeySpec); + + // byte[] encrypted = cipher.doFinal(message.getBytes()); + // System.out.println("encrypted string: " + encrypted); //storing into MySQL DB + // System.out.println("in hex: '" + Convert.toHexString(encrypted) + "'"); + + // cipher.init(Cipher.DECRYPT_MODE, skeySpec); + // byte[] original = cipher.doFinal(encrypted); + // String originalString = new String(original); + // System.out.println("Original string: " + originalString); + // } catch (Exception e) { + // System.err.println("Exception caught: " + e.toString()); + // } + System.exit(0); + + } + +} diff --git a/vid/src/main/java/org/openecomp/vid/encryption/EncryptedPropValue.java b/vid/src/main/java/org/openecomp/vid/encryption/EncryptedPropValue.java new file mode 100644 index 000000000..651df697c --- /dev/null +++ b/vid/src/main/java/org/openecomp/vid/encryption/EncryptedPropValue.java @@ -0,0 +1,279 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.encryption; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +/** + * The Class EncryptedPropValue. + */ +public class EncryptedPropValue { + + /** The encrypted configuration. */ + private EncryptedConfiguration encryptedConfiguration; + + /** The encryption key. */ + private String encryptionKey; + + /** The encryption method. */ + private String encryptionMethod; + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EncryptedPropValue.class); + + /** + * Instantiates a new encrypted prop value. + */ + public EncryptedPropValue() { + // encryptionKey = "57ajqe{kJjjarj}G#(3)ea7"; + encryptionKey = "aa1adm1n"; + encryptionMethod = "AES"; + encryptedConfiguration = new EncryptedConfiguration(encryptionKey, encryptionMethod); + } + + /** + * Gets the encrypted string. + * + * @param f the f + * @param name the name + * @param deflt the deflt + * @return the encrypted string + * @throws Exception the exception + */ + public String getEncryptedString(String f, String name, String deflt) throws Exception { + return encryptedConfiguration.getString(f, name, deflt); + } + + /** + * Generate encrypted property. + * + * @param name the name + * @param value the value + */ + public static void generateEncryptedProperty(String name, String value) { + logger.debug(EELFLoggerDelegate.debugLogger, "==> generateEncryptedProperty"); + EncryptedPropValue aaiPropValue = new EncryptedPropValue(); + try { + System.out.println(name + ".x=" + + EncryptedConfiguration.encryptToTriple( + aaiPropValue.encryptionMethod, + EncryptedConfiguration.generateSalt(), + aaiPropValue.encryptionKey, value)); + } catch (Exception e) { + System.err.println("Cannot encrypt '" + value + "' for property '" + name + "': "+ e.toString()); + } + } + + /** + * Extract property. + * + * @param f the f + * @param name the name + */ + public static void extractProperty(String f, String name) { + EncryptedPropValue aaiPropValue = new EncryptedPropValue(); + String val = ""; + logger.debug(EELFLoggerDelegate.debugLogger, "==> extractProperty"); + try { + val = aaiPropValue.getEncryptedString(f, name, ""); + System.out.println(val); + } catch (Exception e) { + System.err.println("Cannot extract '" + name + "' from '" + f + "': " + e.toString()); + } + } + + /** + * Usage. + */ + public static void usage() { + usage(null); + } + + + /** + * Decrypt triple. + * + * @param triple the triple + * @return the string + */ + public static String decryptTriple(String triple) { + EncryptedPropValue aaiPropValue = new EncryptedPropValue(); + logger.debug(EELFLoggerDelegate.debugLogger, "==> descrptTriple"); + + String out = ""; + try { + //System.out.println(dragonPropValue.encryptedConfiguration.decrypt(triple, dragonPropValue.encryptionKey)); + logger.debug(EELFLoggerDelegate.debugLogger, "calling dragonPropValue.encryptedConfiguration.decrypt()"); + out = EncryptedConfiguration.decrypt(triple, + aaiPropValue.encryptionKey, + aaiPropValue.encryptionMethod, + EncryptedConfiguration.generateSalt()); + //System.out.println("out = " + out); + } catch (Exception e) { + System.err.println("Cannot decrypt '" + triple + "': " + e.toString()); + } + + return out; + } + + /** + * Encrypt input. + */ + public static void encryptInput() { + String s; + + Pattern p = Pattern.compile("^ENCRYPTME[.]([A-Z]*)[.]([^= \t]*)[ \t]*=[ \t]*([^ \t]*)[ \t]*$"); + + EncryptedPropValue aaiPropValue = null; + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + try { + while ((s = in.readLine()) != null) { + Matcher m = p.matcher(s); + if (m.matches()) { + if (aaiPropValue == null) + aaiPropValue = new EncryptedPropValue(); + String method = m.group(1); + String name = m.group(2); + String value = m.group(3); + try { + System.out.println(name + ".x=" + + EncryptedConfiguration.encryptToTriple(method, + EncryptedConfiguration.generateSalt(), + aaiPropValue.encryptionKey, value)); + } catch (Exception e) { + System.err.println("Error: Cannot encrypt '" + value + "', method '" + method + "' for property '" + name + "': " + e.toString()); + } // end of try + } else { + System.out.println(s); + } + } // end of while + } catch (IOException e) { + System.err.println("Error: Cannot read from stdin: " + e.toString()); + } + + } + + /** + * Usage. + * + * @param msg the msg + */ + public static void usage(String msg) { + if (msg != null) System.err.println(msg); + System.err.println("Usage: java EncryptedPropValue -n property -f property-file"); + System.err.println("\tExtract the named value from the given property-file (or full pathname)"); + System.err.println("Usage: java EncryptedPropValue -n property -v value"); + System.err.println("\tEncrypt the given property with the given name and value"); + System.err.println("Usage: java EncryptedPropValue -E"); + System.err.println("\tEncrypt all lines that look like ENCRYPTME.METHOD.name=value"); + System.err.println("Usage: java EncryptedPropValue -u value"); + System.err.println("\tDecrypt the given value, expressed as a single HEXVAL"); + System.exit(1); + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + Options options = new Options(); + options.addOption("n", true, "name"); + options.addOption("f", true, "property-file"); + options.addOption("v", true, "value"); + options.addOption("E", false, "Encrypt all lines that look like ENCRYPTME.METHOD.name=value"); + options.addOption("u", true, "Decrypt the given value, expressed as a single HEXVAL"); + options.addOption("h", false, "show help"); + options.addOption("?", false, "show help"); + + String propfile = null, name = null, value = null, unencrypt = null; + boolean encryptStdin = false; + + CommandLineParser parser = new DefaultParser(); + CommandLine cmd = null; + + try { + cmd = parser.parse(options, args); + + System.out.println("You picked " + cmd.toString() + "\n"); + if (cmd.hasOption("n")) { + name = cmd.getOptionValue("n"); + } + if (cmd.hasOption("f")) { + propfile = cmd.getOptionValue("f"); + } + if (cmd.hasOption("u")) { + unencrypt = cmd.getOptionValue("u"); + } + if (cmd.hasOption("E")) { + encryptStdin = true; + } + if (cmd.hasOption("v")) { + value = cmd.getOptionValue("v"); + } + if (cmd.hasOption("?") || cmd.hasOption("h")) { + usage(); + System.exit(0); + } + + if (encryptStdin) { + if (name != null || propfile != null || value != null) { + usage("cannot use -E with other options"); + } + encryptInput(); + } else if (unencrypt == null) { + if (name == null) usage("-n is required"); + if (propfile == null) { + if (value == null) usage("-v required"); + if (value != null) { + generateEncryptedProperty(name, value); + } + } else { + extractProperty(propfile, name); + } + } else { + String out = decryptTriple(unencrypt); + System.out.println(out); + } + } catch (ParseException e) { + System.out.println("Failed to parse command line properties e="+e.toString()); + } catch (Exception e) { + System.out.println("Failed to run EncryptedConfiguration main() e="+e.toString()); + } + + System.exit(0); + + } + +} |