From f06fbca2e2cc9eaa280303fa5135e271c3abb0ac Mon Sep 17 00:00:00 2001 From: Miek Gieben Date: Sat, 15 Jan 2011 12:18:18 +0100 Subject: [PATCH] Add private (rsa) key to string method --- keygen.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/keygen.go b/keygen.go index c880e608..f3fa2c77 100644 --- a/keygen.go +++ b/keygen.go @@ -2,6 +2,8 @@ package dns import ( "os" + "strconv" + "big" "crypto/rsa" "crypto/rand" ) @@ -59,3 +61,47 @@ func (r *RR_DNSKEY) Generate(bits int) (PrivateKey, os.Error) { } return nil, nil // Dummy return } + +// Convert a PrivateKey to a string. This +// string has the same format as the private-key-file +// of BIND9 (Private-key-format: v1.3). It needs some +// info from the key (hashing, keytag), so its a method +// of the RR_DNSKEY. +func (r *RR_DNSKEY) PrivateKeyToString(p PrivateKey) (s string) { + switch t := p.(type) { + case *rsa.PrivateKey: + algorithm := strconv.Itoa(int(r.Algorithm)) + " (" + alg_str[r.Algorithm] + ")" + modulus := unpackBase64(t.PublicKey.N.Bytes()) + pub := make([]byte, 1) + pub[0] = uint8(t.PublicKey.E) // Todo does not fit with binds 65537 exp! + publicExponent := unpackBase64(pub) + privateExponent := unpackBase64(t.D.Bytes()) + prime1 := unpackBase64(t.P.Bytes()) + prime2 := unpackBase64(t.Q.Bytes()) + // Calculate Exponent1/2 and Coefficient as per: http://en.wikipedia.org/wiki/RSA#Using_the_Chinese_remainder_algorithm + // and from: http://code.google.com/p/go/issues/detail?id=987 + one := big.NewInt(1) + minusone := big.NewInt(-1) + p_1 := big.NewInt(0).Sub(t.P, one) + q_1 := big.NewInt(0).Sub(t.Q, one) + exp1 := big.NewInt(0).Mod(t.D, p_1) + exp2 := big.NewInt(0).Mod(t.D, q_1) + coeff := big.NewInt(0).Exp(t.Q, minusone, t.P) + + exponent1 := unpackBase64(exp1.Bytes()) + exponent2 := unpackBase64(exp2.Bytes()) + coefficient := unpackBase64(coeff.Bytes()) + + s = "Private-key-format: v1.3\n" + + "Algorithm: " + algorithm + "\n" + + "Modules: " + modulus + "\n" + + "PublicExponent: " + publicExponent + "\n" + + "PrivateExponent: " + privateExponent + "\n" + + "Prime1: " + prime1 + "\n" + + "Prime2: " + prime2 + "\n" + + "Exponent1: " + exponent1 + "\n" + + "Exponent2: " + exponent2 + "\n" + + "Coefficient: " + coefficient + "\n" + } + return +}