OSDN Git Service

Merge branch 'master' of https://github.com/Bytom/bytom-btmhash
[bytom/bytom.git] / crypto / crypto.go
1 // Copyright 2014 The go-ethereum Authors
2 // This file is part of the go-ethereum library.
3 //
4 // The go-ethereum library is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Lesser General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // The go-ethereum library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public License
15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16
17 package crypto
18
19 import (
20         "github.com/bytom/common"
21         "golang.org/x/crypto/ripemd160"
22         "golang.org/x/crypto/sha3"
23 )
24
25 func Sha256(data ...[]byte) []byte {
26         d := sha3.New256()
27         for _, b := range data {
28                 d.Write(b)
29         }
30         return d.Sum(nil)
31 }
32
33 func Sha256Hash(data ...[]byte) (h common.Hash) {
34         d := sha3.New256()
35         for _, b := range data {
36                 d.Write(b)
37         }
38         d.Sum(h[:0])
39         return h
40 }
41
42 func Sha3(data ...[]byte) []byte          { return Sha256(data...) }
43 func Sha3Hash(data ...[]byte) common.Hash { return Sha256Hash(data...) }
44
45 func Ripemd160(data []byte) []byte {
46         ripemd := ripemd160.New()
47         ripemd.Write(data)
48
49         return ripemd.Sum(nil)
50 }
51
52 func PubkeyToAddress(pubBytes []byte) common.Address {
53         address, _ := common.AddressEncode("bm", 1, toInt(Ripemd160(Sha3(pubBytes))))
54         return common.StringToAddress(address)
55 }
56
57 func AddressToPubkey(addr common.Address) (int, []byte, error) {
58         ver, data, err := common.AddressDecode("bm", addr.Str())
59         return ver, toBytes(data), err
60 }
61
62 func zeroBytes(bytes []byte) {
63         for i := range bytes {
64                 bytes[i] = 0
65         }
66 }
67
68 func toInt(bytes []byte) []int {
69         ints := make([]int, len(bytes))
70         for i := range bytes {
71                 ints[i] = int(bytes[i])
72         }
73         return ints
74 }
75
76 func toBytes(ints []int) []byte {
77         bytes := make([]byte, len(ints))
78         for i := range ints {
79                 bytes[i] = byte(ints[i])
80         }
81         return bytes
82 }