md5、sha256、sha512

package main

import (
   "crypto/md5"
   "crypto/sha256"
   "crypto/sha512"
   "encoding/hex"
   "fmt"
   "strings"
)

func MD5(str string) string {
   hash := md5.New()
   hash.Write([]byte(str))
   return hex.EncodeToString(hash.Sum(nil))
}

func SHA256(str string) string {
   hash := sha256.New()
   hash.Write([]byte(str))
   return hex.EncodeToString(hash.Sum(nil))
}

func SHA512(str string) string {
   hash := sha512.New()
   hash.Write([]byte(str))
   return hex.EncodeToString(hash.Sum(nil))
}

func main() {
   str := "manong"

   //========== MD5 ==========//
   md5Str := MD5(str)
   fmt.Printf("MD5(\"%+v\") = %+v [大写]\r\n", str, strings.ToUpper(md5Str))
   fmt.Printf("MD5(\"%+v\") = %+v [小写]\r\n", str, strings.ToLower(md5Str))
   // MD5("manong") = 7CD22DAC40674205180B9BE5CC2437DF [大写]
   // MD5("manong") = 7cd22dac40674205180b9be5cc2437df [小写]

   //========== SHA256 ==========//
   sha256Str := SHA256(str)
   fmt.Printf("SHA256(\"%+v\") = %+v [大写]\r\n", str, strings.ToUpper(sha256Str))
   fmt.Printf("SHA256(\"%+v\") = %+v [小写]\r\n", str, strings.ToLower(sha256Str))
   // SHA256("manong") = 33236B98B9DEFF79EAEE4EFE5853E93A0BD7E54C6DA6FE043BE69767A04913F0 [大写]
   // SHA256("manong") = 33236b98b9deff79eaee4efe5853e93a0bd7e54c6da6fe043be69767a04913f0 [小写]

   //========== SHA512 ==========//
   sha512Str := SHA512(str)
   fmt.Printf("SHA512(\"%+v\") = %+v [大写]\r\n", str, strings.ToUpper(sha512Str))
   fmt.Printf("SHA512(\"%+v\") = %+v [小写]\r\n", str, strings.ToLower(sha512Str))
   // SHA512("manong") = C0D8A12732D4AFA2D567152690DD1214DB1174844A78CD603246F29B8EBEF1FA168623AFB465DA916F433CF06BA7CB6883F01B55FEB64947E83FFB92A8325F45 [大写]
   // SHA512("manong") = c0d8a12732d4afa2d567152690dd1214db1174844a78cd603246f29b8ebef1fa168623afb465da916f433cf06ba7cb6883f01b55feb64947e83ffb92a8325f45 [小写]
}

Copyright © 2024 码农人生. All Rights Reserved