| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.cloudsoft.utils;
- import java.util.Properties;
- import javax.crypto.Cipher;
- import javax.crypto.SecretKey;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.PBEParameterSpec;
- /**
- *
- * @author Paul
- */
- public class EncryptedProperties extends Properties {
- private Cipher encrypter, decrypter;
- private static byte[] salt = {(byte) 0x00, 0x04, 0x00, 0x07, 0x01, 0x09, 0x06, 0x07}; // make up your own
- public EncryptedProperties() {
- this(salt);
- }
- public EncryptedProperties(byte[] bSalt) {
- try {
- String pw = "";
- int is = 80;
- while (pw.length() < 20) {
- is = is + pw.length() * ((pw.length()%2 == 1) ? -1:1);
- pw += (char) is;
- }
- PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(bSalt, 20);
- SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
- SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pw.toCharArray()));
- encrypter = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
- decrypter = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
- encrypter.init(Cipher.ENCRYPT_MODE, k, ps);
- decrypter.init(Cipher.DECRYPT_MODE, k, ps);
- } catch (Exception ex) {
- System.out.println(ex.getMessage());
- }
- }
- public String getProperty(String key) {
- try {
- return decrypt(super.getProperty(key));
- } catch (Exception e) {
- throw new RuntimeException("Couldn't decrypt property");
- }
- }
- public synchronized Object setProperty(String key, String value) {
- return setProperty(key, value, true);
- }
- public synchronized Object setProperty(String key, String value, boolean bEncrypt) {
- try {
- return super.setProperty(key, bEncrypt ? encrypt(value) : value);
- } catch (Exception e) {
- throw new RuntimeException("Couldn't encrypt property");
- }
- }
- public synchronized Object setNormalProperty(String key, String value) {
- try {
- return super.setProperty(key, value);
- } catch (Exception e) {
- throw new RuntimeException("Couldn't encrypt property");
- }
- }
- private synchronized String decrypt(String str) throws Exception {
- byte[] dec = Base64.decode(str);
- byte[] utf8 = decrypter.doFinal(dec);
- return new String(utf8, "UTF-8");
- }
- private synchronized String encrypt(String str) throws Exception {
- byte[] utf8 = str.getBytes("UTF-8");
- byte[] enc = encrypter.doFinal(utf8);
- return Base64.encode(enc);
- }
- }
|