All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ats.crypto.Passwords Maven / Gradle / Ivy

The newest version!
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
 */

package com.ats.crypto;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.ats.AtsSingleton;
import com.ats.script.Project;

//-----------------------------------------------------------------------------------------------------------------
// Very simple class to encrypt passwords data /!\ DO NOT USE for very strong encryption or security needs /!\
//-----------------------------------------------------------------------------------------------------------------

public class Passwords implements Serializable {

	private static final long serialVersionUID = -2364261599407176796L;

	private static final String OLD_NAME = "passwords.crypto";

	private transient File file;

	private int keyLen = 16;
	private byte[] masterKey;
	private HashMap data = new HashMap<>();

	public Passwords() {

		InputStream input = getClass().getClassLoader().getResourceAsStream(Project.SECRET_FILE_URL);
		if(input == null) {
			input = getClass().getClassLoader().getResourceAsStream(Project.SRC_FOLDER + "/" + Project.SECRET_FILE_URL);
		}
        
        try {
			load(Base64.getDecoder().decode(input.readAllBytes()));
		} catch (IOException e) {
			sendAtsLogsError(e.getMessage());
		}
	}
	
	public Passwords(Path assetsPath) {
		file = checkFile(assetsPath);
		if(file.exists()) {
			load();
		}else {
			save();
		}
	}

	public Passwords(File assetsFolder) {
		try {
			file = checkFile(assetsFolder.toPath());
			if(file.exists()) {
				load();
			}else {
				file = null;
			}
		}catch(Exception e) {
			file = null;
		}
	}

	private static File checkFile(Path assetsPath) {

		final Path secretFolder = assetsPath.resolve(Project.SECRET_FOLDER);
		File f = secretFolder.resolve(Project.SECRET_FILE).toFile();
		if(f.exists()) {
			return f;
		}

		f = secretFolder.resolve(OLD_NAME).toFile();
		if(f.exists()) {
			try{
				final Path newFilePath = secretFolder.resolve(Project.SECRET_FILE);
				Files.move(f.toPath(), newFilePath);
				return newFilePath.toFile();
			} catch (IOException e) { }
		}

		return secretFolder.resolve(Project.SECRET_FILE).toFile();
	}

	public void setPassword(String key, String value) {
		data.put(key, value.getBytes());
		save();
		load();
	}

	public String getPassword(String key) {
		if(data.containsKey(key)) {
			return new String(data.get(key)).replaceAll("\0", "");
		}
		return "";
	}

	public PasswordData[] getDataList() {

		final List keySet = data.keySet().stream().collect(Collectors.toList());
		Collections.sort(keySet, (o1, o2) -> o1.compareTo(o2));

		final PasswordData[] result = new PasswordData[data.size()];
		int loop = 0;
		for(String key : keySet) {
			result[loop] = new PasswordData(key, getPassword(key));
			loop++;
		}
		return result;
	}

	public void clear() {
		data.clear();
	}

	private String getAtsKey() {
		String key = AtsSingleton.getInstance().getAtsKey();
		if(key != null) {
			return key;
		}else {
			final Project p = Project.getProjectData(file, null, null);
			return p.getAtsKey();
		}
	}

	//-----------------------------------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------------------------------

	private byte[] loadFileBytes() throws IOException {
		byte[] bytes = Base64.getDecoder().decode(Files.readAllBytes(file.toPath()));
		final String atsKey = getAtsKey();
		if(atsKey != null) {
			bytes = decrypt(atsKey.getBytes(), bytes);
		}
		return bytes;
	}

	private void saveFileBytes(byte[] bytes) throws IOException {
		final String atsKey = getAtsKey();
		if(atsKey != null) {
			bytes = encrypt(atsKey.getBytes(), bytes);
		}
		Files.write(file.toPath(), Base64.getEncoder().encode(bytes));
	}
	
	private void load() {
		try {
			load(loadFileBytes());
		} catch (IOException e) {
			sendAtsLogsError(e.getMessage());
		}
	}

	private void load(byte[] b) {
		try {

			ByteArrayInputStream bis = new ByteArrayInputStream(b);

			byte[] key = new byte[keyLen];
			bis.read(key, 0, keyLen);

			byte[] bytes = decrypt(key, bis.readAllBytes());
			bis.close();

			final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
			final ObjectInputStream objStream = new ObjectInputStream(byteStream);

			final Passwords pass = (Passwords) objStream.readObject();
			data = pass.data;
			masterKey = pass.masterKey;

		} catch (Exception e) {
			sendAtsLogsError(e.getMessage());
			return;
		}

		data.replaceAll((k, v) -> decrypt(masterKey, v));
	}

	private void save() {
		try {

			file.getParentFile().mkdirs();

			final byte[] randomKey = new byte[keyLen];
			masterKey = new byte[keyLen];

			final SecureRandom random = SecureRandom.getInstanceStrong();
			random.nextBytes(randomKey);
			random.nextBytes(masterKey);

			data.replaceAll((k, v) -> encrypt(masterKey, v));

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			final ObjectOutput out = new ObjectOutputStream(bos);
			out.writeObject(this);

			final byte[] dataBytes = encrypt(randomKey, bos.toByteArray());
			out.close();
			bos.close();

			bos = new ByteArrayOutputStream();
			bos.write(randomKey);
			bos.write(dataBytes);

			saveFileBytes(bos.toByteArray());
			bos.close();

		} catch (NoSuchAlgorithmException | IOException e) {
			sendAtsLogsError(e.getMessage());
		}
	}
	
	synchronized private static Cipher getCipher() {

		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
		} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {

		}

		return cipher;
	}
	
	private static byte[] encrypt(byte[] key, byte[] data) {
		try {

			SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
			IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);

			Cipher cipher = getCipher();
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

			return cipher.doFinal(data);

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}
	
	private byte[] decrypt(byte[] key, byte[] data) {
		try {

			SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
			IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);

			Cipher cipher = getCipher();
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);

			return cipher.doFinal(data);

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}

	/*private static byte[] encrypt(byte[] key, byte[] data) {
		cipher.init(true, new KeyParameter(key));
		byte[] rv = new byte[cipher.getOutputSize(data.length)];
		int tam = cipher.processBytes(data, 0, data.length, rv, 0);
		try {
			cipher.doFinal(rv, tam);
		} catch (Exception e) {}
		return rv;
	}*/
	
	/*private byte[] decrypt(byte[] key, byte[] data) {
		cipher.init(false, new KeyParameter(key));
		byte[] rv = new byte[cipher.getOutputSize(data.length)];
		int tam = cipher.processBytes(data, 0, data.length, rv, 0);
		try {
			cipher.doFinal(rv, tam);
		} catch (Exception e) {}
		return rv;
	}*/

	private static void sendAtsLogsError(String message) {
		System.err.println("[ATS-ENCRYPT-EXCEPTION]\n" + message);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy