Srinivas M
Srinivas M

Reputation: 313

SHA256 Base64 Hash in Ruby

We are trying to implement the SHA256 Base64 hash in ruby which is not returning the expected results as in C#.

Below is our C# sample code.

    public static string HashSHA256ToBase64(string phrase)
    {
        if (phrase == null)
            return null;
        var encoder = new UTF8Encoding();
        var sha256Hasher = new SHA256CryptoServiceProvider();
        var hashedDataBytes = sha256Hasher.ComputeHash(encoder.GetBytes(phrase));

        return Convert.ToBase64String(hashedDataBytes);
    }

For this, we need to write equivalent code in ruby. For which we are trying as follows.

Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), "", phrase))

It is not providing the same results as C#.

Test phrase : V2dcZBpzzglD1ynW5ZAyFocs9wtpR624wlla9gujw0I=RquZ/QzazPM=

Expected Result : utXwt733s9FmiSM69o2zGOm0IT42FjthbB0oquIuPak=

Can someone help me with the equivalent ruby code to resolve this

Upvotes: 2

Views: 3529

Answers (1)

Srinivas M
Srinivas M

Reputation: 313

Below code fixed this

Digest::SHA256.base64digest(phrase)

Upvotes: 8

Related Questions