Debian Codegraph @

dh/ecdh/curve25519.go

raw symbols SCIP
1 // Use of this source code is governed by a license
2 // that can be found in the LICENSE file.
3
4 package ecdh
5
6 import (
7 cryptorand "crypto/rand"
8 "errors"
9 "io"
10
11 "golang.org/x/crypto/curve25519"
12 )
13
14 type ecdh25519 struct{}
15
16 // Curve25519 creates a new ecdh.KeyExchange with
17 // the elliptic curve Curve25519.
18 func Curve25519() KeyExchange {
19 return ecdh25519{}
20 }
21
22 func (c ecdh25519) GenerateKey(rand io.Reader) (private PrivateKey, public PublicKey, err error) {
23 if rand == nil {
24 rand = cryptorand.Reader
25 }
26
27 var pri, pub [32]byte
28 _, err = io.ReadFull(rand, pri[:])
29 if err != nil {
30 return
31 }
32
33 // From https://cr.yp.to/ecdh.html
34 pri[0] &= 248
35 pri[31] &= 127
36 pri[31] |= 64
37
38 curve25519.ScalarBaseMult(&pub, &pri)
39
40 private = pri[:]
41 public = pub[:]
42 return
43 }
44
45 func (c ecdh25519) PublicKey(private PrivateKey) (public PublicKey) {
46 if len(private) != 32 {
47 panic("ecdh: private key is not 32 byte")
48 }
49
50 var pri, pub [32]byte
51 copy(pri[:], private)
52
53 curve25519.ScalarBaseMult(&pub, &pri)
54
55 public = pub[:]
56 return
57 }
58
59 func (c ecdh25519) Check(peersPublic PublicKey) (err error) {
60 if len(peersPublic) != 32 {
61 err = errors.New("peers public key is not 32 byte")
62 }
63 return
64 }
65
66 func (c ecdh25519) ComputeSecret(private PrivateKey, peersPublic PublicKey) (secret []byte) {
67 if len(private) != 32 {
68 panic("ecdh: private key is not 32 byte")
69 }
70 if len(peersPublic) != 32 {
71 panic("ecdh: peers public key is not 32 byte")
72 }
73
74 var sec, pri, pub [32]byte
75 copy(pri[:], private)
76 copy(pub[:], peersPublic)
77
78 curve25519.ScalarMult(&sec, &pri, &pub)
79
80 secret = sec[:]
81 return
82 }