This repository has been archived on 2024-04-07. You can view files and clone it, but cannot push or open issues or pull requests.
moneroutil/key.go

68 lines
1.2 KiB
Go
Raw Permalink Normal View History

2017-05-11 19:15:06 +00:00
package moneroutil
import (
"crypto/rand"
2017-05-20 10:04:57 +00:00
"io"
2017-05-11 19:15:06 +00:00
)
const (
2017-05-14 00:36:32 +00:00
KeyLength = 32
2017-05-11 19:15:06 +00:00
)
2017-05-14 00:36:32 +00:00
// Key can be a Scalar or a Point
type Key [KeyLength]byte
2017-05-11 19:15:06 +00:00
2017-05-14 00:36:32 +00:00
func (p *Key) FromBytes(b [KeyLength]byte) {
2017-05-11 19:15:06 +00:00
*p = b
}
2017-05-14 00:36:32 +00:00
func (p *Key) ToBytes() (result [KeyLength]byte) {
result = [KeyLength]byte(*p)
2017-05-11 19:15:06 +00:00
return
}
2017-05-14 00:36:32 +00:00
func (p *Key) PubKey() (pubKey *Key) {
2017-05-11 19:15:06 +00:00
point := new(ExtendedGroupElement)
2017-05-14 00:36:32 +00:00
GeScalarMultBase(point, p)
pubKey = new(Key)
point.ToBytes(pubKey)
2017-05-11 19:15:06 +00:00
return
}
// Creates a point on the Edwards Curve by hashing the key
2017-05-14 00:36:32 +00:00
func (p *Key) HashToEC() (result *ExtendedGroupElement) {
2017-05-11 19:15:06 +00:00
result = new(ExtendedGroupElement)
var p1 ProjectiveGroupElement
var p2 CompletedGroupElement
2017-05-14 00:36:32 +00:00
h := Key(Keccak256(p[:]))
2017-05-11 19:15:06 +00:00
p1.FromBytes(&h)
GeMul8(&p2, &p1)
p2.ToExtended(result)
return
}
2017-05-14 00:36:32 +00:00
func RandomScalar() (result *Key) {
result = new(Key)
var reduceFrom [KeyLength * 2]byte
tmp := make([]byte, KeyLength*2)
2017-05-11 19:15:06 +00:00
rand.Read(tmp)
copy(reduceFrom[:], tmp)
2017-05-14 00:36:32 +00:00
ScReduce(result, &reduceFrom)
2017-05-11 19:15:06 +00:00
return
}
2017-05-14 00:36:32 +00:00
func NewKeyPair() (privKey *Key, pubKey *Key) {
privKey = RandomScalar()
2017-05-11 19:15:06 +00:00
pubKey = privKey.PubKey()
return
}
2017-05-20 10:04:57 +00:00
func ParseKey(buf io.Reader) (result Key, err error) {
key := make([]byte, KeyLength)
if _, err = buf.Read(key); err != nil {
return
}
copy(result[:], key)
return
}