-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.go
More file actions
78 lines (66 loc) · 2.31 KB
/
Copy pathcrypto.go
File metadata and controls
78 lines (66 loc) · 2.31 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/nacl/box"
)
const (
X25519PublicKeySize = 32
NonceSize = 24
)
// GenerateX25519KeyPair generates a new X25519 key pair
func GenerateX25519KeyPair() (privateKey, publicKey [32]byte, err error) {
// Generate random private key
if _, err := io.ReadFull(rand.Reader, privateKey[:]); err != nil {
return privateKey, publicKey, fmt.Errorf("failed to generate private key: %w", err)
}
// Derive public key from private key
pub, err := curve25519.X25519(privateKey[:], curve25519.Basepoint)
if err != nil {
return privateKey, publicKey, fmt.Errorf("failed to derive public key: %w", err)
}
copy(publicKey[:], pub)
return privateKey, publicKey, nil
}
// EncryptForMobile encrypts a message for a mobile device using NaCl box
// Returns hex-encoded: nonce (24 bytes) + ciphertext
func EncryptForMobile(message string, mobilePublicKeyHex string, pcPrivateKey [32]byte) (string, error) {
// Decode mobile's public key
mobilePublicKeyBytes, err := hex.DecodeString(mobilePublicKeyHex)
if err != nil {
return "", fmt.Errorf("invalid mobile public key: %w", err)
}
if len(mobilePublicKeyBytes) != X25519PublicKeySize {
return "", fmt.Errorf("mobile public key wrong size: got %d, want %d", len(mobilePublicKeyBytes), X25519PublicKeySize)
}
var mobilePublicKey [32]byte
copy(mobilePublicKey[:], mobilePublicKeyBytes)
// Generate random nonce
var nonce [NonceSize]byte
if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
return "", fmt.Errorf("failed to generate nonce: %w", err)
}
// Encrypt using NaCl box
encrypted := box.Seal(nil, []byte(message), &nonce, &mobilePublicKey, &pcPrivateKey)
// Combine nonce + ciphertext
result := make([]byte, NonceSize+len(encrypted))
copy(result[:NonceSize], nonce[:])
copy(result[NonceSize:], encrypted)
return hex.EncodeToString(result), nil
}
// GetPrivateKeyFromHex converts a hex-encoded private key to [32]byte
func GetPrivateKeyFromHex(hexKey string) ([32]byte, error) {
var key [32]byte
bytes, err := hex.DecodeString(hexKey)
if err != nil {
return key, fmt.Errorf("invalid hex key: %w", err)
}
if len(bytes) != 32 {
return key, fmt.Errorf("key wrong size: got %d, want 32", len(bytes))
}
copy(key[:], bytes)
return key, nil
}