Examples of crypto package


func SHA1(s string) []byte {         
    h := sha1.New()                  
    io.WriteString(h, s)             
    v := h.Sum(nil)                  
    fmt.Printf("%x\n", v)            
    return v                         
}                                    
                                     
func SHA256(s string) [32]byte {     
    h := sha256.New()                
    h.Write([]byte(s))               
    v := h.Sum(nil)                  
    fmt.Printf("%x\n", v)            
                                     
    sum := sha256.Sum256([]byte(s))  
    fmt.Printf("%x\n", sum)          
                                     
    return sum                       
}                                    
                                     
func MD5(s string) []byte {          
    h := md5.New()                   
    io.WriteString(h, s)             
    sum := h.Sum(nil)                
    fmt.Printf("%x\n", sum)          
    return sum                       
}                                    
                                     
func HashPassword(pwd, pepper string) ([]byte, error) {
    mac := hmac.New(sha256.New, []byte(pepper))
    mac.Write([]byte(pwd))           
    sum := mac.Sum(nil)              
    fmt.Printf("sha256 sum: %x\n", sum)
    pwdDigest := base64.StdEncoding.EncodeToString(sum)
    pwdDigest = strings.TrimRight(pwdDigest, "=")
    fmt.Printf("md: %v\n", pwdDigest)                                                             
    d, err := bcrypt.GenerateFromPassword([]byte(pwdDigest), 12)
    fmt.Printf("bcrypt: %s\n", string(d))
    return d, err                    
}  

func PasswordMatchesHash(pwd, hash, pepper string) bool {
    mac := hmac.New(sha256.New, []byte(pepper))
    mac.Write([]byte(pwd))
    pwdDigest := base64.StdEncoding.EncodeToString(mac.Sum(nil))
    pwdDigest = strings.TrimRight(pwdDigest, "=")
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwdDigest))
    return err == nil
}                  



  


Comments:

Write a comment
Anonymous

Captcha image

Reload

Type the number you see in the image above: