github.com/igggame/nebulas-go@v2.1.0+incompatible/crypto/hash/hash.go (about) 1 // Copyright (C) 2017 go-nebulas authors 2 // 3 // This file is part of the go-nebulas library. 4 // 5 // the go-nebulas library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // the go-nebulas library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 19 package hash 20 21 import ( 22 "crypto/sha256" 23 "encoding/base64" 24 25 keccak "github.com/nebulasio/go-nebulas/crypto/sha3" 26 "golang.org/x/crypto/ripemd160" 27 "golang.org/x/crypto/sha3" 28 ) 29 30 // const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 31 const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" 32 33 var bcEncoding = base64.NewEncoding(alphabet) 34 35 // Sha256 returns the SHA-256 digest of the data. 36 func Sha256(args ...[]byte) []byte { 37 hasher := sha256.New() 38 for _, bytes := range args { 39 hasher.Write(bytes) 40 } 41 return hasher.Sum(nil) 42 } 43 44 // Sha3256 returns the SHA3-256 digest of the data. 45 func Sha3256(args ...[]byte) []byte { 46 hasher := sha3.New256() 47 for _, bytes := range args { 48 hasher.Write(bytes) 49 } 50 return hasher.Sum(nil) 51 } 52 53 // Keccak256 returns the Keccak-256 digest of the data. 54 func Keccak256(data ...[]byte) []byte { 55 d := keccak.NewKeccak256() 56 for _, b := range data { 57 d.Write(b) 58 } 59 return d.Sum(nil) 60 } 61 62 // Ripemd160 return the RIPEMD160 digest of the data. 63 func Ripemd160(args ...[]byte) []byte { 64 hasher := ripemd160.New() 65 for _, bytes := range args { 66 hasher.Write(bytes) 67 } 68 return hasher.Sum(nil) 69 } 70 71 // Base64Encode encode to base64 72 func Base64Encode(src []byte) []byte { 73 n := bcEncoding.EncodedLen(len(src)) 74 dst := make([]byte, n) 75 bcEncoding.Encode(dst, src) 76 // for dst[n-1] == '=' { 77 // n-- 78 // } 79 return dst[:n] 80 } 81 82 // Base64Decode decode base64 83 func Base64Decode(src []byte) ([]byte, error) { 84 numOfEquals := 4 - (len(src) % 4) 85 for i := 0; i < numOfEquals; i++ { 86 src = append(src, '=') 87 } 88 89 dst := make([]byte, bcEncoding.DecodedLen(len(src))) 90 n, err := bcEncoding.Decode(dst, src) 91 if err != nil { 92 return nil, err 93 } 94 return dst[:n], nil 95 }