Home > database >  Convert hex string hash to base64
Convert hex string hash to base64

Time:03-25

I have a plaintext password "welcome2022".

Expected SHA1 hash is wjC4KfO5XfMIRhi45M/VA/0i8NA=

However, SHA1 hash method of sql is generating SHA1 hash in hex string format which is C230B829F3B95DF3084618B8E4CFD503FD22F0D0.

I intend to convert the the above hex string to the base64 encoded hash wjC4KfO5XfMIRhi45M/VA/0i8NA=.

Below is the groovy code for your reference.

    def cleartext = SecurityUtil.decrypt(password) //Decrypts the value of a GuardedString.    
   def password_bytes = [0, 0, 0, 0, 0] as byte[]
    password_bytes = SecurityUtil.charsToBytes(cleartext.toCharArray())
    def password2 = SecurityUtil.computeBase64SHA1Hash(password_bytes) //Computes the base 64 encoded SHA1 hash of the input.

Then running the below sql query,

sql.eachRow("SELECT id FROM users WHERE userName = ? AND password =CONCAT('{SHA1}', ?)", [username, password2]) {
....
}

Logs do not show any errors when this groovy script is executed.

I am not sure if I am writing the code correct syntactically.

CodePudding user response:

So this function will give you the base64 encoded SHA-1 hash of a given password:

def sha64(String password) {
    password.digest('SHA-1').decodeHex().encodeBase64()
}

And if you do:

println sha64('welcome2022')

It prints

wjC4KfO5XfMIRhi45M/VA/0i8NA=
  • Related