File: sharedkey.go

package info (click to toggle)
golang-github-jedisct1-xsecretbox 1.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 88 kB
  • sloc: makefile: 2
file content (27 lines) | stat: -rw-r--r-- 654 bytes parent folder | download
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
package xsecretbox

import (
	crypto_rand "crypto/rand"

	"golang.org/x/crypto/chacha20"
	"golang.org/x/crypto/curve25519"
)

// SharedKey computes a shared secret compatible with the one used by `crypto_box_xchacha20poly1305`
func SharedKey(secretKey [32]byte, publicKey [32]byte) ([32]byte, error) {
	dhKey, err := curve25519.X25519(secretKey[:], publicKey[:])
	var subKey []byte
	if err == nil {
		var nonce [16]byte
		subKey, err = chacha20.HChaCha20(dhKey[:], nonce[:])
	}
	var key [32]byte
	if err != nil {
		if _, err2 := crypto_rand.Read(key[:]); err != nil {
			return key, err2
		}
		return key, err
	}
	copy(key[:], subKey)
	return key, nil
}