Created
October 16, 2023 14:52
-
-
Save Oxygenesis/830332ff054dee0fa2d984424f585a47 to your computer and use it in GitHub Desktop.
Digest mozzila implementation in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/sha256" | |
"encoding/hex" | |
"fmt" | |
"github.com/armortal/webcrypto-go" | |
"github.com/armortal/webcrypto-go/algorithms/sha" | |
"github.com/opencontainers/go-digest" | |
) | |
func main() { | |
// Implementation of https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest in golang | |
// Sample values for demonstration | |
data := "data" | |
// Creating the digest using default function from golang | |
result := defaultDigest(data) | |
fmt.Println("Default Digest:", result) | |
// Creating the digest with webcrypto-go | |
result, err := webcryptoDigest(data) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("WebCrypto Digest:", result) | |
// Creating the digest with go-digest | |
result = goDigest(data) | |
fmt.Println("Go-digest Digest:", result) | |
// summary: every one of them resulting the same result | |
} | |
func defaultDigest(data string) string { | |
hash := sha256.Sum256([]byte(data)) | |
return hex.EncodeToString(hash[:]) | |
} | |
func webcryptoDigest(data string) (string, error) { | |
hash, err := webcrypto.Subtle().Digest( | |
&sha.Algorithm{ | |
Name: "SHA-256", | |
}, []byte(data), | |
) | |
if err != nil { | |
return "", err | |
} | |
return fmt.Sprintf("%x", hash), nil | |
} | |
func goDigest(data string) string { | |
return digest.FromBytes([]byte(data)).String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment