Removing plain text passwords in Gradle

on Friday 5 April 2013

To ensure no plain text passwords are stored on the servers the following piece of code can be used encrypt and decrypt passwords.


 import java.security.*  
 import javax.crypto.*  
 import javax.crypto.spec.*  
 class DESCodec {  
   static encode = { String target ->  
     def cipher = getCipher(Cipher.ENCRYPT_MODE)  
     return cipher.doFinal(target.bytes).encodeBase64()  
   }  
   static decode = { String target ->  
     def cipher = getCipher(Cipher.DECRYPT_MODE)  
     return new String(cipher.doFinal(target.decodeBase64()))  
   }  
   private static getCipher(mode) {  
     def keySpec = new DESKeySpec(getPassword())  
     def cipher = Cipher.getInstance("DES")  
     def keyFactory = SecretKeyFactory.getInstance("DES")  
     cipher.init(mode, keyFactory.generateSecret(keySpec))  
     return cipher  
   }  
   private static getPassword() { "secret12".getBytes("UTF-8") }  
 }  

Things to note in this script are:

  • encode - this method takes a string, encodes the string against a key and returns an encoded string
  • decode - this method takes the encoded string and key and decodes to the plain text password
  • key - this is the string that is set to "secret12" in the code above. This should be changed and owned
  • on a per environment basis. To further improve ease of use this should be parameterised.

Usage:



 task setPassword << {   
   println new DESCodec().encode("password")  
 }  
 task getPassword << {   
   println new DESCodec().decode("VGf1XPEzkT7g6D2EhjMlrg==")  
 }  

How you use this in your gradle script is entirely up to you. One suggestion I have would be to pass in the
Key as a parameter to your script.

0 comments:

Post a Comment