1. 程式人生 > >kettle 資料庫連線密碼的加密

kettle 資料庫連線密碼的加密

開啟kettle的資源庫配置檔案respositories.xml,可以看到資料庫的連線密碼是加密的。

例如

<username/>
    <password>Encrypted sasdfere13rrrf</password>

加解密由org.pentaho.di.core.encryption.Encr負責,演算法非常簡單:

public static final String encryptPassword(String password)
	{
		if (password==null) return "";
		if (password.length()==0) return "";
		
		BigInteger bi_passwd = new BigInteger(password.getBytes());
		
		BigInteger bi_r0  = new BigInteger(SEED);
		BigInteger bi_r1  = bi_r0.xor(bi_passwd);
		
		return bi_r1.toString(RADIX); 
	}

	public static final String decryptPassword(String encrypted)
	{
		if (encrypted==null) return "";
		if (encrypted.length()==0) return "";
		
		BigInteger bi_confuse  = new BigInteger(SEED);
		
		try
		{
			BigInteger bi_r1 = new BigInteger(encrypted, RADIX);
			BigInteger bi_r0 = bi_r1.xor(bi_confuse);
			
			return new String(bi_r0.toByteArray()); 
		}
		catch(Exception e)
		{
			return "";
		}
	}

資料庫密碼如果需要加密,儲存後來會以特定字元開頭

public  static final String PASSWORD_ENCRYPTED_PREFIX = "Encrypted ";

加密方法,被加一個方法呼叫

 public static final String encryptPasswordIfNotUsingVariables(String password)
    {
        String encrPassword = "";
        List<String> varList = new ArrayList<String>();
        StringUtil.getUsedVariables(password, varList, true);
        if (varList.isEmpty())
        {
            encrPassword = PASSWORD_ENCRYPTED_PREFIX+Encr.encryptPassword(password);
        }
        else
        {
            encrPassword = password;
        }
        
        return encrPassword;
    }

是否加密,由StringUtil的方法決定

public static void getUsedVariables(String aString, List<String> list, boolean includeSystemVariables)
	{
		getUsedVariables(aString, UNIX_OPEN, UNIX_CLOSE, list, includeSystemVariables);
		getUsedVariables(aString, WINDOWS_OPEN, WINDOWS_CLOSE, list, includeSystemVariables);
	}

如果密碼是使用變數的方法,就不會加密,即%%變數%%和${變數}的方式填寫,就不會加密。如果將變數調到Java的系統屬性中,開啟資源庫時,就可以使用。