github.com/fighterlyt/hugo@v0.47.1/tpl/crypto/crypto.go (about) 1 // Copyright 2017 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package crypto 15 16 import ( 17 "crypto/md5" 18 "crypto/sha1" 19 "crypto/sha256" 20 "encoding/hex" 21 22 "github.com/spf13/cast" 23 ) 24 25 // New returns a new instance of the crypto-namespaced template functions. 26 func New() *Namespace { 27 return &Namespace{} 28 } 29 30 // Namespace provides template functions for the "crypto" namespace. 31 type Namespace struct{} 32 33 // MD5 hashes the given input and returns its MD5 checksum. 34 func (ns *Namespace) MD5(in interface{}) (string, error) { 35 conv, err := cast.ToStringE(in) 36 if err != nil { 37 return "", err 38 } 39 40 hash := md5.Sum([]byte(conv)) 41 return hex.EncodeToString(hash[:]), nil 42 } 43 44 // SHA1 hashes the given input and returns its SHA1 checksum. 45 func (ns *Namespace) SHA1(in interface{}) (string, error) { 46 conv, err := cast.ToStringE(in) 47 if err != nil { 48 return "", err 49 } 50 51 hash := sha1.Sum([]byte(conv)) 52 return hex.EncodeToString(hash[:]), nil 53 } 54 55 // SHA256 hashes the given input and returns its SHA256 checksum. 56 func (ns *Namespace) SHA256(in interface{}) (string, error) { 57 conv, err := cast.ToStringE(in) 58 if err != nil { 59 return "", err 60 } 61 62 hash := sha256.Sum256([]byte(conv)) 63 return hex.EncodeToString(hash[:]), nil 64 }