Friday, May 23, 2014

Simple SecurePasswordVault in Java

There are some instances, you want to store your passwords in files to be used by the programs or scripts. But storing your passwords in plain text is not a good idea. Use the SecurePasswordVault to encrypt your passwords before storing and get it decrypted when you want to use it.

You can use the SecurePasswordVault described here to store any number of encrypted passwords. Passwords are stored as key value pairs.

Key - any name given by the user for the password
Value - encrypted password

SecurePasswordVault will create a file with the given name in the working directory if it doesn't exist. If a file exist then the information in that file will be read.

Passwords are encrypted using the MAC address of the network card. SecurePasswordVault will use the first network card MAC which is not the loop back interface. So the encrypted file can only be decrypted with that particular MAC address. If you want to reset the pass word details, just delete the password file and run the SecurePasswordVault.

You can download the sample code from the following Github repository
https://github.com/jsdjayanga/secure_password

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package com.wso2.devgov;

import org.bouncycastle.util.encoders.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.*;

/**
* Created by jayanga on 3/31/14.
*/
public class SecurePasswordVault {

    private static final int AES_KEY_LEN = 32;
    private static final int PASSWORD_LEN = 256;
    
    private static boolean initialized;
    private final String secureFile;
    private final byte[] networkHardwareHaddress;
    private Map<String, String> secureDataMap;
    private List<String> secureDataList;

    SecretKeySpec secretKey;

    public SecurePasswordVault(String filename, String[] secureData) throws IOException {

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        initialized = false;
        secureFile = filename;
        networkHardwareHaddress = SecurePasswordVault.readNetworkHardwareAddress();
        secureDataMap = new HashMap<String, String>();

        this.secureDataList = new ArrayList<String>(secureData.length);
        Collections.addAll(secureDataList, secureData);

        byte[] key = new byte[AES_KEY_LEN];
        Arrays.fill(key, (byte)0);

        for(int index = 0; index < networkHardwareHaddress.length; index++){
            key[index] = networkHardwareHaddress[index];
        }

        secretKey = new SecretKeySpec(key, "AES");

        if (!isInitialized()){
            readSecureData(secureDataList);
            persistSecureData();
        }

        readSecureDataFromFile();
    }
    
    private boolean isInitialized(){
        if (initialized == true){
            return true;
        }else{
            File file = new File(secureFile);
            if (file.exists()){
                initialized = true;
                return initialized;
            }
        }
        return false;
    }

    private static byte[] readNetworkHardwareAddress() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        if (networkInterfaceEnumeration != null){
            NetworkInterface networkInterface = null;
            while (networkInterfaceEnumeration.hasMoreElements()){
                networkInterface = networkInterfaceEnumeration.nextElement();
                if (!networkInterface.isLoopback()){
                    break;
                }
            }

            if (networkInterface == null){
                networkInterface = networkInterfaceEnumeration.nextElement();
            }

            byte[] hwaddr = networkInterface.getHardwareAddress();

            return hwaddr;
        }else{
            throw new RuntimeException("Cannot initialize. Failed to generate unique id.");
        }
    }

    private byte[] encrypt(String word) {
        byte[] password = new byte[PASSWORD_LEN];
        Arrays.fill(password, (byte)0);

        byte[] pw = new byte[0];

        try {
            pw = word.getBytes("UTF-8");

            for(int index = 0; index < pw.length; index++){
                password[index] = pw[index];
            }

            byte[] cipherText = new byte[password.length];

            Cipher cipher = null;
            try {
                cipher = Cipher.getInstance("AES/ECB/NoPadding");

                try {
                    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

                    int ctLen = 0;
                    try {
                        ctLen = cipher.update(password, 0, password.length, cipherText, 0);
                        ctLen += cipher.doFinal(cipherText, ctLen);

                        return cipherText;
                    } catch (ShortBufferException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    }
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    private String decrypt(byte[] cipherText) {
        byte[] plainText = new byte[PASSWORD_LEN];

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/NoPadding");

            try {
                cipher.init(Cipher.DECRYPT_MODE, secretKey);

                int plainTextLen = 0;
                try {
                    plainTextLen = cipher.update(cipherText, 0, PASSWORD_LEN, plainText, 0);

                    try {
                        plainTextLen += cipher.doFinal(plainText, plainTextLen);
                        String password = new String(plainText);
                        return password.trim();

                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    }
                } catch (ShortBufferException e) {
                    e.printStackTrace();
                }


            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }

    public void readSecureData(List<String> secureDataList) throws IOException {
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

        for(int index = 0; index < secureDataList.size(); index++){
            System.out.println("Please enter the value for :" + secureDataList.get(index));

            String value = new String(Base64.encode(encrypt(bufferRead.readLine())));
            secureDataMap.put(secureDataList.get(index), value);
        }
    }

    public String getSecureData(String key) {
        String value = secureDataMap.get(key);
        if (value != null){
            return decrypt(Base64.decode(value.getBytes()));
        }

        throw new RuntimeException("Given key is unknown. [key=" + key + "]");
    }

    private void readSecureDataFromFile() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(secureFile));

        String line;
        while ((line = br.readLine()) != null){
            int dividerPoint = line.indexOf("=");
            if (dividerPoint > 0){
                secureDataMap.put(line.substring(0, dividerPoint), line.substring(dividerPoint + 1));
            }
        }
    }

    private void persistSecureData() throws IOException {
        FileWriter fileWriter = new FileWriter(secureFile);

        for(String key : secureDataMap.keySet()){
            fileWriter.append(key + "=" + secureDataMap.get(key) + "\n");
        }

        fileWriter.close();
    }
}


No comments:

Post a Comment