1package dns
2
3import (
4	"crypto"
5	"crypto/ecdsa"
6	"crypto/ed25519"
7	"crypto/rsa"
8	"math/big"
9	"strconv"
10)
11
12const format = "Private-key-format: v1.3\n"
13
14var bigIntOne = big.NewInt(1)
15
16// PrivateKeyString converts a PrivateKey to a string. This string has the same
17// format as the private-key-file of BIND9 (Private-key-format: v1.3).
18// It needs some info from the key (the algorithm), so its a method of the DNSKEY.
19// It supports *rsa.PrivateKey, *ecdsa.PrivateKey and ed25519.PrivateKey.
20func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string {
21	algorithm := strconv.Itoa(int(r.Algorithm))
22	algorithm += " (" + AlgorithmToString[r.Algorithm] + ")"
23
24	switch p := p.(type) {
25	case *rsa.PrivateKey:
26		modulus := toBase64(p.PublicKey.N.Bytes())
27		e := big.NewInt(int64(p.PublicKey.E))
28		publicExponent := toBase64(e.Bytes())
29		privateExponent := toBase64(p.D.Bytes())
30		prime1 := toBase64(p.Primes[0].Bytes())
31		prime2 := toBase64(p.Primes[1].Bytes())
32		// Calculate Exponent1/2 and Coefficient as per: http://en.wikipedia.org/wiki/RSA#Using_the_Chinese_remainder_algorithm
33		// and from: http://code.google.com/p/go/issues/detail?id=987
34		p1 := new(big.Int).Sub(p.Primes[0], bigIntOne)
35		q1 := new(big.Int).Sub(p.Primes[1], bigIntOne)
36		exp1 := new(big.Int).Mod(p.D, p1)
37		exp2 := new(big.Int).Mod(p.D, q1)
38		coeff := new(big.Int).ModInverse(p.Primes[1], p.Primes[0])
39
40		exponent1 := toBase64(exp1.Bytes())
41		exponent2 := toBase64(exp2.Bytes())
42		coefficient := toBase64(coeff.Bytes())
43
44		return format +
45			"Algorithm: " + algorithm + "\n" +
46			"Modulus: " + modulus + "\n" +
47			"PublicExponent: " + publicExponent + "\n" +
48			"PrivateExponent: " + privateExponent + "\n" +
49			"Prime1: " + prime1 + "\n" +
50			"Prime2: " + prime2 + "\n" +
51			"Exponent1: " + exponent1 + "\n" +
52			"Exponent2: " + exponent2 + "\n" +
53			"Coefficient: " + coefficient + "\n"
54
55	case *ecdsa.PrivateKey:
56		var intlen int
57		switch r.Algorithm {
58		case ECDSAP256SHA256:
59			intlen = 32
60		case ECDSAP384SHA384:
61			intlen = 48
62		}
63		private := toBase64(intToBytes(p.D, intlen))
64		return format +
65			"Algorithm: " + algorithm + "\n" +
66			"PrivateKey: " + private + "\n"
67
68	case ed25519.PrivateKey:
69		private := toBase64(p.Seed())
70		return format +
71			"Algorithm: " + algorithm + "\n" +
72			"PrivateKey: " + private + "\n"
73
74	default:
75		return ""
76	}
77}
78