File: key.go

package info (click to toggle)
golang-github-cloudflare-circl 1.0.0%2B20200724-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,788 kB
  • sloc: asm: 19,418; ansic: 1,289; makefile: 54
file content (47 lines) | stat: -rw-r--r-- 1,170 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package x25519

import (
	"crypto/subtle"

	fp "github.com/cloudflare/circl/math/fp25519"
)

// Size is the length in bytes of a X25519 key.
const Size = 32

// Key represents a X25519 key.
type Key [Size]byte

func (k *Key) clamp(in *Key) *Key {
	*k = *in
	k[0] &= 248
	k[31] = (k[31] & 127) | 64
	return k
}

// isValidPubKey verifies if the public key is not a low-order point.
func (k *Key) isValidPubKey() bool {
	fp.Modp((*fp.Elt)(k))
	isLowOrder := false
	for _, P := range lowOrderPoints {
		isLowOrder = isLowOrder || subtle.ConstantTimeCompare(P[:], k[:]) != 0
	}
	return !isLowOrder
}

// KeyGen obtains a public key given a secret key.
func KeyGen(public, secret *Key) {
	ladderJoye(public.clamp(secret))
}

// Shared calculates Alice's shared key from Alice's secret key and Bob's
// public key returning true on success. A failure case happens when the public
// key is a low-order point, thus the shared key is all-zeros and the function
// returns false.
func Shared(shared, secret, public *Key) bool {
	validPk := *public
	validPk[31] &= (1 << (255 % 8)) - 1
	ok := validPk.isValidPubKey()
	ladderMontgomery(shared.clamp(secret), &validPk)
	return ok
}