diff options
Diffstat (limited to 'security-utils')
7 files changed, 0 insertions, 663 deletions
diff --git a/security-utils/.gitignore b/security-utils/.gitignore deleted file mode 100644 index ae3c172604..0000000000 --- a/security-utils/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/security-utils/logback-test.xml b/security-utils/logback-test.xml deleted file mode 100644 index 4b7eb955c7..0000000000 --- a/security-utils/logback-test.xml +++ /dev/null @@ -1,13 +0,0 @@ -<!-- only one line, shut up logback ! --> -<configuration > - <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> - <encoder> - <Pattern> - %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n - </Pattern> - </encoder> - </appender> - <root level="OFF"> - <appender-ref ref="STDOUT" /> - </root> -</configuration> diff --git a/security-utils/pom.xml b/security-utils/pom.xml deleted file mode 100644 index 19fea32c1f..0000000000 --- a/security-utils/pom.xml +++ /dev/null @@ -1,96 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - - <modelVersion>4.0.0</modelVersion> - - <artifactId>security-utils</artifactId> - - <parent> - <groupId>org.openecomp.sdc</groupId> - <artifactId>sdc-main</artifactId> - <version>1.6.0-SNAPSHOT</version> - </parent> - - <dependencies> - - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>${junit.version}</version> - <scope>test</scope> - </dependency> - - <!-- slf4j + logback --> - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>${slf4j-api.version}</version> - <scope>compile</scope> - </dependency> - <!-- functional java --> - <dependency> - <groupId>org.functionaljava</groupId> - <artifactId>functionaljava</artifactId> - <version>${functionaljava.version}</version> - <scope>compile</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-assembly-plugin</artifactId> - <executions> - <execution> - <id>create.jar.with.dependencies</id> - <phase>package</phase> - <goals> - <goal>single</goal> - </goals> - <configuration> - <archive> - <manifest> - <mainClass>org.openecomp.sdc.security.Passwords</mainClass> - </manifest> - </archive> - <descriptorRefs> - <descriptorRef>jar-with-dependencies</descriptorRef> - </descriptorRefs> - </configuration> - </execution> - </executions> - </plugin> - <plugin> - <groupId>com.github.sylvainlaurent.maven</groupId> - <artifactId>yaml-json-validator-maven-plugin</artifactId> - <executions> - <execution> - <id>validate</id> - <phase>validate</phase> - <goals> - <goal>validate</goal> - </goals> - <configuration> - <validationSets> - <validationSet> - <includes> - <include>src/main/resources/**/*.y*ml</include> - <include>src/test/resources/**/*.y*ml</include> - </includes> - </validationSet> - <validationSet> - <includes> - <include>src/main/resources/**/*.json</include> - <include>src/test/resources/**/*.json</include> - </includes> - </validationSet> - </validationSets> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - -</project> diff --git a/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java b/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java deleted file mode 100644 index 48c8523354..0000000000 --- a/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java +++ /dev/null @@ -1,190 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.sdc.security; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Random; - - -public class Passwords { - - private static Logger log = LoggerFactory.getLogger( Passwords.class); - private static final Random RANDOM = new SecureRandom(); - private static final int SALT = 0; - private static final int HASH = 1; - private static final String HASH_ALGORITHM = "SHA-256"; - - /** - * static utility class - */ - private Passwords() { - } - - /** - * the method calculates a hash with a generated salt for the given password - * - * @param password - * @return a "salt:hash" value - */ - public static String hashPassword(String password) { - if (password!=null){ - byte[] salt = getNextSalt(); - byte[] byteData = hash(salt, password.getBytes()); - if (byteData != null) { - return toHex(salt) + ":" + toHex(byteData); - } - } - return null; - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param expectedHash - * @return - */ - public static boolean isExpectedPassword(String password, String expectedHash) { - if (password==null && expectedHash==null) - return true; - if (password==null || expectedHash==null) //iff exactly 1 is null - return false; - if (!expectedHash.contains(":")){ - log.error("invalid password expecting hash at the prefix of the password (ex. e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0)\n" + - "\t\t\t"); - return false; - } - String[] params = expectedHash.split(":"); - return isExpectedPassword(password, params[SALT], params[HASH]); - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param salt - * @param hash - * the hash generated using the salt - * @return true if the password matched the hash - */ - public static boolean isExpectedPassword(String password, String salt, String hash) { - if ( password == null && hash == null ) - return true; - if ( salt == null ){ - log.error("salt must be initialized"); - return false; - } - //unintialized params - if ( password == null || hash == null ) - return false; - byte[] saltBytes = fromHex(salt); - byte[] hashBytes = fromHex(hash); - - byte[] byteData = hash(saltBytes, password.getBytes()); - if (byteData != null) { - return Arrays.equals(byteData, hashBytes); - } - return false; - } - - public static void main(String[] args) { - if (args.length > 1 || args.length > 0) { - System.out.println("[" + hashPassword(args[0]) + "]"); - } else { - System.out.println("no passward passed."); - } - - } - - /** - * Returns a random salt to be used to hash a password. - * - * @return a 16 bytes random salt - */ - private static byte[] getNextSalt() { - byte[] salt = new byte[16]; - RANDOM.nextBytes(salt); - return salt; - } - - /** - * hase's the salt and value using the chosen algorithm - * - * @param salt - * @param password - * @return an array of bytes resulting from the hash - */ - private static byte[] hash(byte[] salt, byte[] password) { - MessageDigest md; - byte[] byteData = null; - try { - md = MessageDigest.getInstance(HASH_ALGORITHM); - md.update(salt); - md.update(password); - byteData = md.digest(); - } catch (NoSuchAlgorithmException e) { - log.error("invalid algorithm name {}", e); - System.out.println("invalid algorithm name"); - } - return byteData; - } - - /** - * Converts a string of hexadecimal characters into a byte array. - * - * @param hex - * the hex string - * @return the hex string decoded into a byte array - */ - private static byte[] fromHex(String hex) { - if ( hex == null ) - return null; - byte[] binary = new byte[hex.length() / 2]; - for (int i = 0; i < binary.length; i++) { - binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); - } - return binary; - } - - /** - * Converts a byte array into a hexadecimal string. - * - * @param array - * the byte array to convert - * @return a length*2 character string encoding the byte array - */ - private static String toHex(byte[] array) { - BigInteger bi = new BigInteger(1, array); - String hex = bi.toString(16); - int paddingLength = (array.length * 2) - hex.length(); - if (paddingLength > 0) - return String.format("%0" + paddingLength + "d", 0) + hex; - else - return hex; - } -} diff --git a/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java b/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java deleted file mode 100644 index bc20e0e991..0000000000 --- a/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java +++ /dev/null @@ -1,217 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 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.sdc.security; - -import fj.data.Either; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.SecretKeySpec; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import java.util.Formatter; - -public class SecurityUtil { - - private static final Logger LOG = LoggerFactory.getLogger( SecurityUtil.class ); - private static final byte[] KEY = new byte[]{-64,5,-32 ,-117 ,-44,8,-39, 1, -9, 36,-46,-81, 62,-15,-63,-75}; - public static final SecurityUtil INSTANCE = new SecurityUtil(); - public static final String ALGORITHM = "AES" ; - public static final String CHARSET = StandardCharsets.UTF_8.name(); - - private static Key secKey = null ; - - private SecurityUtil(){ super(); } - - /** - * - * cmd commands >$PROGRAM_NAME decrypt "$ENCRYPTED_MSG" - * >$PROGRAM_NAME encrypt "message" - **/ - public static void main(String[] args) throws Exception { - if ( args!=null && args.length>1){ - fj.data.Either res = null; - final String op = args[0].trim().toLowerCase(); - try{ - switch(op) { - case "decrypt": - res = INSTANCE.decrypt(Base64.getDecoder().decode(args[1]), true); - break; - case "encrypt": - res = INSTANCE.encrypt(args[1]); - break; - default: - LOG.warn("Unfamiliar command please use: \n>aes <encrypt/decrypt> 'message to encrypt/decrypt' "); - } - }catch(Exception e){ - LOG.warn("Exception while message encryption or decryption"); - throw e; - } - LOG.debug( "output: {}", res!=null && res.isLeft() ? res.left().value() : "ERROR" ); - } - } - - - static { - Formatter formatter = new Formatter(); - try{ - secKey = generateKey( KEY, ALGORITHM ); - } - catch(Exception e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("cannot generate key for %s", ALGORITHM).toString(), e); - } - }finally { - formatter.close(); - } - } - - - - public static Key generateKey(final byte[] key, String algorithm){ - return new SecretKeySpec(key, algorithm); - } - - //obfuscates key prefix -> ********** - public String obfuscateKey(String sensitiveData){ - - if (sensitiveData != null){ - int len = sensitiveData.length(); - StringBuilder builder = new StringBuilder(sensitiveData); - for (int i=0; i<len/2; i++){ - builder.setCharAt(i, '*'); - } - return builder.toString(); - } - return sensitiveData; - } - - /** - * @param strDataToEncrypt - plain string to encrypt - * Encrypt the Data - * a. Declare / Initialize the Data. Here the data is of type String - * b. Convert the Input Text to Bytes - * c. Encrypt the bytes using doFinal method - */ - public Either<String,String> encrypt(String strDataToEncrypt){ - - if (strDataToEncrypt != null ){ - Formatter formatter = new Formatter(); - try{ - LOG.debug("Encrypt key -> {}", secKey); - Cipher aesCipherForEncryption = Cipher.getInstance("AES"); // Must specify the mode explicitly as most JCE providers default to ECB mode!! - aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secKey); - byte[] byteDataToEncrypt = strDataToEncrypt.getBytes(); - byte[] byteCipherText = aesCipherForEncryption.doFinal(byteDataToEncrypt); - String strCipherText = new String( java.util.Base64.getMimeEncoder().encode(byteCipherText), CHARSET ); - LOG.debug("Cipher Text generated using AES is {}", strCipherText); - return Either.left(strCipherText); - } catch( NoSuchAlgorithmException | UnsupportedEncodingException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("cannot encrypt data unknown algorithm or missing encoding for %s",secKey.getAlgorithm()).toString(), e); - } - } catch( InvalidKeyException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("invalid key recieved - > %s", java.util.Base64.getDecoder().decode(secKey.getEncoded())).toString(), e); - } - } catch( IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn("bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding", e); - } - } - finally { - formatter.close(); - } - } - return Either.right("Cannot encrypt "+strDataToEncrypt); - } - - /** - * Decrypt the Data - * @param byteCipherText - should be valid bae64 input in the length of 16bytes - * @param isBase64Decoded - is data already base64 encoded&aligned to 16 bytes - * a. Initialize a new instance of Cipher for Decryption (normally don't reuse the same object) - * b. Decrypt the cipher bytes using doFinal method - */ - public Either<String,String> decrypt(byte[] byteCipherText , boolean isBase64Decoded){ - if (byteCipherText != null){ - byte[] alignedCipherText = byteCipherText; - Formatter formatter = new Formatter(); - try{ - if (isBase64Decoded) - alignedCipherText = Base64.getDecoder().decode(byteCipherText); - LOG.debug("Decrypt key -> {}", secKey.getEncoded()); - Cipher aesCipherForDecryption = Cipher.getInstance("AES"); // Must specify the mode explicitly as most JCE providers default to ECB mode!! - aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secKey); - byte[] byteDecryptedText = aesCipherForDecryption.doFinal(alignedCipherText); - String strDecryptedText = new String(byteDecryptedText); - String obfuscateKey = obfuscateKey( strDecryptedText ); - LOG.debug("Decrypted Text message is: {}" , obfuscateKey); - return Either.left(strDecryptedText); - } catch( NoSuchAlgorithmException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("cannot encrypt data unknown algorithm or missing encoding for %s", secKey.getAlgorithm()).toString(), e); - } - } catch( InvalidKeyException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("invalid key recieved - > %s", java.util.Base64.getDecoder().decode(secKey.getEncoded())).toString(), e); - } - } catch( IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn( "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding", e); - } - }finally { - formatter.close(); - } - } - return Either.right("Decrypt FAILED"); - } - - public Either<String,String> decrypt(String byteCipherText){ - Formatter formatter = new Formatter(); - try { - return decrypt(byteCipherText.getBytes(CHARSET),true); - } catch( UnsupportedEncodingException e ){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("Missing encoding for %s",secKey.getAlgorithm()).toString(), e); - } - }finally { - formatter.close(); - } - return Either.right("Decrypt FAILED"); - } -} diff --git a/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java b/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java deleted file mode 100644 index 9310917ba1..0000000000 --- a/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 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.sdc.security; - -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class PasswordsTest { - - @Test - public void hashPassword() throws Exception { - String hash = Passwords.hashPassword("hello1234"); - assertTrue(Passwords.isExpectedPassword("hello1234", hash)); - - //test different salt-> result in different hash - String hash2 = Passwords.hashPassword("hello1234"); - assertFalse(hash.equals(hash2)); - - String hash3 = Passwords.hashPassword(""); - assertTrue(Passwords.isExpectedPassword("", hash3)); - - String hash4 = Passwords.hashPassword(null); - assertTrue(hash4 == null); - } - - @Test - public void isExpectedPassword() throws Exception { - //region isExpectedPassword(String password, String salt, String hash) - assertTrue(Passwords.isExpectedPassword(null, null, null)); - //valid hash - assertTrue(Passwords.isExpectedPassword("hello1234", "e0277df331f4ff8f74752ac4a8fbe03b", "6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //invalid salt - assertFalse(Passwords.isExpectedPassword("hello1234", "c0000df331f4ff8f74752ac4a00be03c", "6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - assertFalse(Passwords.isExpectedPassword("hello1234", null, "6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //exacly 1 param uninitialized - assertFalse(Passwords.isExpectedPassword("hello1234", "", null)); - assertFalse(Passwords.isExpectedPassword(null, "", "hello1234")); - //no salt & no hash - assertFalse(Passwords.isExpectedPassword("hello1234", null, "hello1234")); - //endregion - - //region isExpectedPassword(String password, String expectedHash) - assertTrue(Passwords.isExpectedPassword(null, null)); - //valid hash - assertTrue(Passwords.isExpectedPassword("hello1234", "e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //invalid salt - assertFalse(Passwords.isExpectedPassword("hello1234", "c0000df331f4ff8f74752ac4a00be03c:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //exacly 1 param uninitialized - assertFalse(Passwords.isExpectedPassword("hello1234", null)); - assertFalse(Passwords.isExpectedPassword(null, "hello1234")); - //no salt & no hash - assertFalse(Passwords.isExpectedPassword("hello1234", "hello1234")); - //endregion - } - - @Test - public void hashtest() { - String password = "123456"; - String hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = "1sdfgsgd23456"; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = "1sdfgsgd2345((*&%$%6"; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = ""; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = " "; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - } - - -} diff --git a/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java b/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java deleted file mode 100644 index e114a468e4..0000000000 --- a/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 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.sdc.security; - -import org.junit.Test; - -import java.util.Base64; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -public class SecurityUtilTest { - - @Test - public void encryptDecryptAES128() throws Exception { - String data = "decrypt SUCCESS!!"; - String encrypted = SecurityUtil.INSTANCE.encrypt(data).left().value(); - assertNotEquals( data, encrypted ); - byte[] decryptMsg = Base64.getDecoder().decode(encrypted); - assertEquals( SecurityUtil.INSTANCE.decrypt( decryptMsg , false ).left().value() ,data ); - assertEquals( SecurityUtil.INSTANCE.decrypt( encrypted.getBytes() , true ).left().value() ,data ); - } - - @Test - public void obfuscateKey() throws Exception { - String key = "abcdefghij123456"; - String expectedkey = "********ij123456"; - String obfuscated = SecurityUtil.INSTANCE.obfuscateKey( key ); - System.out.println( obfuscated ); - assertEquals( obfuscated , expectedkey ); - } -} |