You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dnssec_privkey.go 2.3KB

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