Skip to content

Commit

Permalink
TRUNK-5205 Use java8 Base64 instead of xerces
Browse files Browse the repository at this point in the history
replaced use of org.apache.xerces.impl.dv.util.Base64
with java8 Base64

added small refactorings TestInstallUtil.getResourceInputStream
* extracted private methods to improve readability
* renamed parameter
* use parametrized log message style and remove if since log.info
already checks for the log level

set checkstyle rule: Import from illegal package - org.apache.xerces
  • Loading branch information
teleivo committed Aug 13, 2017
1 parent d237db5 commit ca2ccfe
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 35 deletions.
12 changes: 7 additions & 5 deletions api/src/main/java/org/openmrs/util/Security.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;

import javax.crypto.Cipher;
Expand All @@ -22,7 +23,6 @@
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.xerces.impl.dv.util.Base64;
import org.openmrs.api.APIException;
import org.openmrs.api.context.Context;
import org.slf4j.Logger;
Expand Down Expand Up @@ -227,11 +227,13 @@ public static String encrypt(String text, byte[] initVector, byte[] secretKey) {
IvParameterSpec initVectorSpec = new IvParameterSpec(initVector);
SecretKeySpec secret = new SecretKeySpec(secretKey, OpenmrsConstants.ENCRYPTION_KEY_SPEC);
byte[] encrypted;
String result;

try {
Cipher cipher = Cipher.getInstance(OpenmrsConstants.ENCRYPTION_CIPHER_CONFIGURATION);
cipher.init(Cipher.ENCRYPT_MODE, secret, initVectorSpec);
encrypted = cipher.doFinal(text.getBytes(encoding));
result = new String(Base64.getEncoder().encode(encrypted), encoding);
}
catch (GeneralSecurityException e) {
throw new APIException("could.not.encrypt.text", null, e);
Expand All @@ -240,7 +242,7 @@ public static String encrypt(String text, byte[] initVector, byte[] secretKey) {
throw new APIException("system.cannot.find.encoding", new Object[] { encoding }, e);
}

return Base64.encode(encrypted);
return result;
}

/**
Expand Down Expand Up @@ -275,7 +277,7 @@ public static String decrypt(String text, byte[] initVector, byte[] secretKey) {
try {
Cipher cipher = Cipher.getInstance(OpenmrsConstants.ENCRYPTION_CIPHER_CONFIGURATION);
cipher.init(Cipher.DECRYPT_MODE, secret, initVectorSpec);
byte[] original = cipher.doFinal(Base64.decode(text));
byte[] original = cipher.doFinal(Base64.getDecoder().decode(text));
decrypted = new String(original, encoding);
}
catch (GeneralSecurityException e) {
Expand Down Expand Up @@ -311,7 +313,7 @@ public static byte[] getSavedInitVector() {
OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY, OpenmrsConstants.ENCRYPTION_VECTOR_DEFAULT);

if (StringUtils.hasText(initVectorText)) {
return Base64.decode(initVectorText);
return Base64.getDecoder().decode(initVectorText);
}

throw new APIException("no.encryption.initialization.vector.found", (Object[]) null);
Expand Down Expand Up @@ -343,7 +345,7 @@ public static byte[] getSavedSecretKey() {
OpenmrsConstants.ENCRYPTION_KEY_DEFAULT);

if (StringUtils.hasText(keyText)) {
return Base64.decode(keyText);
return Base64.getDecoder().decode(keyText);
}

throw new APIException("no.encryption.secret.key.found", (Object[]) null);
Expand Down
9 changes: 6 additions & 3 deletions api/src/test/java/org/openmrs/util/SecurityTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
*/
package org.openmrs.util;

import org.apache.xerces.impl.dv.util.Base64;
import java.util.Base64;
import java.util.Base64.Decoder;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.StringUtils;
Expand Down Expand Up @@ -73,9 +75,10 @@ public void hashMatches_shouldMatchStringsHashedWithIncorrectSha1Algorithm() {
*/
@Test
public void decrypt_shouldDecryptShortAndLongText() {
final Decoder base64 = Base64.getDecoder();
// use specific IV and Key
byte[] initVector = Base64.decode("9wyBUNglFCRVSUhMfsTa3Q==");
byte[] secretKey = Base64.decode("dTfyELRrAICGDwzjHDjuhw==");
byte[] initVector = base64.decode("9wyBUNglFCRVSUhMfsTa3Q==");
byte[] secretKey = base64.decode("dTfyELRrAICGDwzjHDjuhw==");

// perform decryption
String expected = "this is fantasmic";
Expand Down
2 changes: 1 addition & 1 deletion checkstyle.xml
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
<property name="severity" value="error"/>
</module>
<module name="IllegalImport">
<property name="illegalPkgs" value="sun, org.apache.commons.logging, org.openmrs.test.Verifies" />
<property name="illegalPkgs" value="sun, org.apache.commons.logging, org.openmrs.test.Verifies, org.apache.xerces" />
<property name="severity" value="error"/>
</module>
<module name="OneTopLevelClass">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
Expand All @@ -42,7 +44,6 @@
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.xerces.impl.dv.util.Base64;
import org.openmrs.ImplementationId;
import org.openmrs.api.APIAuthenticationException;
import org.openmrs.api.PasswordException;
Expand Down Expand Up @@ -1508,10 +1509,11 @@ public void run() {
}
runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString());
runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString());
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY, Base64.encode(Security
.generateNewInitVector()));
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY, Base64.encode(Security
.generateNewSecretKey()));
final Encoder base64 = Base64.getEncoder();
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY,
new String(base64.encode(Security.generateNewInitVector())));
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY,
new String(base64.encode(Security.generateNewSecretKey())));

Properties properties = Context.getRuntimeProperties();
properties.putAll(runtimeProperties);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.xerces.impl.dv.util.Base64;
import org.openmrs.api.APIAuthenticationException;
import org.openmrs.api.APIException;
import org.openmrs.api.context.Context;
Expand Down Expand Up @@ -252,41 +253,51 @@ protected static boolean testConnection(String urlString) {
}

/**
* @param urlString
* @param url
* @param openmrsUsername
* @param openmrsPassword
* @return input stream
* @throws MalformedURLException
* @throws IOException
*/
protected static InputStream getResourceInputStream(String urlString, String openmrsUsername, String openmrsPassword)
protected static InputStream getResourceInputStream(String url, String openmrsUsername, String openmrsPassword)
throws MalformedURLException, IOException, APIException {

HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(15000);
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);

String requestParams = "username=" + Base64.encode(openmrsUsername.getBytes(Charset.forName("UTF-8")))
+ "&password=" + Base64.encode(openmrsPassword.getBytes(Charset.forName("UTF-8")));

OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(requestParams);
HttpURLConnection connection = createConnection(url);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(encodeCredentials(openmrsUsername, openmrsPassword));
out.flush();
out.close();

if (log.isInfoEnabled()) {
log.info("Http response message:" + urlConnection.getResponseMessage() + ", Code:"
+ urlConnection.getResponseCode());
}
log.info("Http response message: {}, Code: {}", connection.getResponseMessage(), connection.getResponseCode());

if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new APIAuthenticationException("Invalid username or password");
} else if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
} else if (connection.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
throw new APIException("error.occurred.on.remote.server", (Object[]) null);
}

return urlConnection.getInputStream();
return connection.getInputStream();
}

private static HttpURLConnection createConnection(String url)
throws IOException, MalformedURLException {
final HttpURLConnection result = (HttpURLConnection) new URL(url).openConnection();
result.setRequestMethod("POST");
result.setConnectTimeout(15000);
result.setUseCaches(false);
result.setDoOutput(true);
return result;
}

private static String encodeCredentials(String openmrsUsername, String openmrsPassword) {
final StringBuilder result = new StringBuilder();
result.append("username=");
final Encoder encoder = Base64.getEncoder();
final Charset utf8 = Charset.forName("UTF-8");
result.append(new String(encoder.encode(openmrsUsername.getBytes(utf8)), utf8));
result.append("&password=");
result.append(new String(encoder.encode(openmrsPassword.getBytes(utf8)), utf8));
return result.toString();
}
}

0 comments on commit ca2ccfe

Please sign in to comment.