Thursday, November 4, 2010

Generating SHA256 passwords in Python

n my last post I had a small example showing how to secure your passwords using Spring Security 3.0.4. We needed a simple client written in Python to do the same from a command line. Of course, if you were using Java, it would have been four lines written in a simple Main class and you could run it in either Eclipse or NetBeans and get the hash of the password.

    public static String passwordEncoder(String plainText) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-256");
            digest.reset();

            byte rawPassword[] = digest.digest(plainText.getBytes("UTF-8"));
            String hash = (new BASE64Encoder()).encode(rawPassword);
            return hash;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
Since we needed a simple command line utility to do the same, to write the same in Python was even more simpler. This example was run on my Ubuntu Virtual machine.

import getpass
from hashlib import sha256
import base64
    def main(self):
        self.generate_hash_password()
       
    def generate_hash_password(self):
       
        print "Enter password to hash :",
        password1 = getpass.getpass()
        print "Confirm :",
        password2 = getpass.getpass()
        if password1 == password2:
            print "Both passwords matched"
            hash = sha256(password1).digest()
            encoded = base64.b64encode(hash)
            print " SHA 256 base 64 encoded password ", ":", encoded
        else:
            print "Both passwords do not match"

   
if __name__ == "__main__":
    try:
        password_encoder = PASSWORD_ENCODER()
        password_encoder.main()
    except KeyboardInterrupt:
        exit(0)

Now run this from a command line as shown below:


The getpass library doesn't echo the password on the command line. Simple and easy.
.

1 comment: