Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding method for decrypt the encrypted text. #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,21 +50,46 @@ public class CipherTool {
public static void main(String[] args) {

initialize(args);
Cipher cipher = KeyStoreUtil.initializeCipher();
Cipher cipher;
if (System.getProperty(Constants.CONFIGURE) != null &&
System.getProperty(Constants.CONFIGURE).equals(Constants.TRUE)) {
System.getProperty(Constants.CONFIGURE).equals(Constants.TRUE)) {
cipher = KeyStoreUtil.initializeCipher(Boolean.FALSE);
loadXpathValuesAndPasswordDetails();
secureVaultConfigTokens();
encryptCipherTextFile(cipher);
Utils.writeToSecureConfPropertyFile();
} else if (System.getProperty(Constants.CHANGE) != null &&
System.getProperty(Constants.CHANGE).equals(Constants.TRUE)) {
System.getProperty(Constants.CHANGE).equals(Constants.TRUE)) {
cipher = KeyStoreUtil.initializeCipher(Boolean.FALSE);
changePassword(cipher);
} else if (System.getProperty(Constants.DECRYPT) != null &&
System.getProperty(Constants.DECRYPT).equals(Constants.TRUE)) {
cipher = KeyStoreUtil.initializeCipher(Boolean.TRUE);
decryptedValue(cipher);
} else {
cipher = KeyStoreUtil.initializeCipher(Boolean.FALSE);
encryptedValue(cipher);
}
}

private static void decryptedValue(Cipher cipher) {
String encryptedKey = Utils.getValueFromConsole("Enter Encrypted text : ", false);
if (!encryptedKey.isEmpty()) {
String decryptedText = null;
try {
byte[] decryptedbyte = cipher.doFinal(DatatypeConverter.parseBase64Binary(encryptedKey));
decryptedText = new String(decryptedbyte);
System.out.println("\nDecrypted value is : \n" + decryptedText + "\n");
} catch (IllegalBlockSizeException e) {
throw new CipherToolException("Error : Cannot decrypt the value", e);
} catch (BadPaddingException e) {
throw new CipherToolException("Error : Cannot decrypt the value", e);
}
} else {
throw new CipherToolException("Error : Invalid input");
}
}

/**
* init the mode of operation of cipher tool using command line argument
*
Expand All @@ -82,7 +107,10 @@ private static void initialize(String[] args) {
System.setProperty(property, Constants.TRUE);
} else if (property.equals(Constants.CHANGE)) {
System.setProperty(property, Constants.TRUE);
} else if (property.length() >= 8 && property.substring(0, 8).equals(Constants.CONSOLE_PASSWORD_PARAM)) {
} else if (property.equals(Constants.DECRYPT)) {
System.setProperty(property, Constants.TRUE);
} else if (property.length() >= 8 &&
property.substring(0, 8).equals(Constants.CONSOLE_PASSWORD_PARAM)) {
System.setProperty(Constants.KEYSTORE_PASSWORD, property.substring(9));
} else {
System.out.println("This option is not define!");
Expand All @@ -103,16 +131,18 @@ private static void printHelp() {
System.out.println("Options :\n");

System.out.println("\t-Dconfigure\t\t This option would allow user to secure plain text passwords in carbon " +
"configuration files. CipherTool will replace all the passwords listed in " +
"cipher-text.properties file with encrypted values and modify related password elements " +
"in the configuration files with secret alias names. Also secret-conf.properties file is " +
"modified with the default configuration data");
"configuration files. CipherTool will replace all the passwords listed in " +
"cipher-text.properties file with encrypted values and modify related password elements " +
"in the configuration files with secret alias names. Also secret-conf.properties file is " +
"modified with the default configuration data");

System.out.println("\t-Dchange\t\t This option would allow user to change the specific password which has " +
"been secured\n");
"been secured\n");
System.out.println("\t-Ddecrypt\t\t This option would allow user to decrypt and get the value when when the " +
"encrypted text provided.");
System.out.println("\t-Dpassword=<password>\t This option would allow user to provide the password as a " +
"command line argument. NOTE: Providing the password in command line arguments list is " +
"not recommended.\n");
"command line argument. NOTE: Providing the password in command line arguments list is " +
"not recommended.\n");
}

/**
Expand All @@ -135,8 +165,8 @@ private static void encryptedValue(Cipher cipher) {
/**
* encrypt the plain text password
*
* @param cipher init cipher
* @param plainTextPwd plain text password
* @param cipher init cipher
* @param plainTextPwd plain text password
* @return encrypted password
*/
private static String doEncryption(Cipher cipher, String plainTextPwd) {
Expand Down Expand Up @@ -190,7 +220,7 @@ private static void secureVaultConfigTokens() {
String fileName = unprocessedXpath.substring(0, endofFilePath);
if (unprocessedXpath.indexOf(",") > 0) {
if ((unprocessedXpath.substring(unprocessedXpath.indexOf(",") + 1)).trim().equals("true") &&
unprocessedXpath.charAt(unprocessedXpath.indexOf(",") - 1) == ']') {
unprocessedXpath.charAt(unprocessedXpath.indexOf(",") - 1) == ']') {
encryptParamKey = unprocessedXpath
.substring(unprocessedXpath.lastIndexOf('[') + 2, unprocessedXpath.indexOf(",") - 1);
}
Expand Down Expand Up @@ -236,7 +266,7 @@ private static void tokenToConfigFile(String fileName, String xPath, String secr
if (node != null) {
if (!encryptParamKey.isEmpty()) {
node.getAttributes().getNamedItem(encryptParamKey)
.setNodeValue(Constants.SecureVault.PASSWORD);
.setNodeValue(Constants.SecureVault.PASSWORD);
} else {
node.setTextContent(Constants.SecureVault.PASSWORD);
}
Expand All @@ -246,7 +276,7 @@ private static void tokenToConfigFile(String fileName, String xPath, String secr
} else {
throw new CipherToolException(
"Element for secret alias '" + secretAlias + "' can not be found in " +
fileName + " file or You have entered invalid Xpath value");
fileName + " file or You have entered invalid Xpath value");
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Expand Down Expand Up @@ -300,7 +330,8 @@ private static void encryptCipherTextFile(Cipher cipher) {

/**
* returns the encrypted value entered via the Console for the given Secret Alias
* @param key key
*
* @param key key
* @param cipher cipher
* @return encrypted value
*/
Expand Down Expand Up @@ -346,7 +377,7 @@ private static void changePassword(Cipher cipher) {
if (isModified) {
cipherTextProperties.putAll(aliasPasswordMap);
Utils.writeToPropertyFile(cipherTextProperties,
System.getProperty(Constants.CIPHER_TEXT_PROPERTY_FILE_PROPERTY));
System.getProperty(Constants.CIPHER_TEXT_PROPERTY_FILE_PROPERTY));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public class Constants {
public static final String CIPHER_STANDALONE_CONFIG_PROPERTY_FILE = "cipher-standalone-config.properties";
public static final String SECRET_PROPERTY_FILE_PROPERTY = "secret.conf.properties.file";
public static final String CIPHER_TRANSFORMATION_SYSTEM_PROPERTY = "org.wso2.CipherTransformation";
public static final String DECRYPT = "decrypt";

public static final class PrimaryKeyStore {
public static final String PRIMARY_KEY_LOCATION_XPATH = "//Server/Security/KeyStore/Location";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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
* 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,
Expand All @@ -28,39 +28,45 @@
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;

public class KeyStoreUtil {

/**
* Initializes the Cipher
* @return cipher cipher
*/
public static Cipher initializeCipher() {
public static Cipher initializeCipher(boolean isDecrypt) {
Cipher cipher;
String keyStoreFile = System.getProperty(Constants.PrimaryKeyStore.PRIMARY_KEY_LOCATION_PROPERTY);
String keyType = System.getProperty(Constants.PrimaryKeyStore.PRIMARY_KEY_TYPE_PROPERTY);
String keyAlias = System.getProperty(Constants.PrimaryKeyStore.PRIMARY_KEY_ALIAS_PROPERTY);
String password;
if (System.getProperty(Constants.KEYSTORE_PASSWORD) != null &&
System.getProperty(Constants.KEYSTORE_PASSWORD).length() > 0) {
System.getProperty(Constants.KEYSTORE_PASSWORD).length() > 0) {
password = System.getProperty(Constants.KEYSTORE_PASSWORD);
} else {
password = Utils.getValueFromConsole("Please Enter Primary KeyStore Password of Carbon Server : ", true);
}
if (password == null) {
throw new CipherToolException("KeyStore password can not be null");
}

KeyStore primaryKeyStore = getKeyStore(keyStoreFile, password, keyType);
try {
Certificate certs = primaryKeyStore.getCertificate(keyAlias);
String cipherTransformation = System.getProperty(Constants.CIPHER_TRANSFORMATION_SYSTEM_PROPERTY);
if (cipherTransformation != null) {
cipher = Cipher.getInstance(cipherTransformation);
} else {
cipher = Cipher.getInstance("RSA");
}
cipher.init(Cipher.ENCRYPT_MODE, certs);
if (!isDecrypt) {
Certificate certs = primaryKeyStore.getCertificate(keyAlias);
cipher.init(Cipher.ENCRYPT_MODE, certs);
} else {
PrivateKey privateKey = (PrivateKey) primaryKeyStore.getKey(keyAlias, password.toCharArray());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
}
} catch (KeyStoreException e) {
throw new CipherToolException("Error initializing Cipher ", e);
} catch (NoSuchAlgorithmException e) {
Expand All @@ -69,6 +75,8 @@ public static Cipher initializeCipher() {
throw new CipherToolException("Error initializing Cipher ", e);
} catch (InvalidKeyException e) {
throw new CipherToolException("Error initializing Cipher ", e);
} catch (UnrecoverableKeyException e) {
throw new CipherToolException("Error initializing Cipher ", e);
}

System.out.println("\nPrimary KeyStore of Carbon Server is initialized Successfully\n");
Expand Down