key.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package crypto
  2. import (
  3. "bytes"
  4. "strings"
  5. )
  6. // ParsePublicKey parse raw public key to pem formation
  7. func ParsePublicKey(raw string) (result []byte) {
  8. return parseKey(raw, "-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----")
  9. }
  10. // ParsePrivateKey parse raw priv key to pem formation
  11. func ParsePrivateKey(raw string) (result []byte) {
  12. return parseKey(raw, "-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----")
  13. }
  14. func parseKey(raw, prefix, suffix string) (result []byte) {
  15. raw = strings.Replace(raw, prefix, "", 1)
  16. raw = strings.Replace(raw, suffix, "", 1)
  17. raw = strings.Replace(raw, " ", "", -1)
  18. raw = strings.Replace(raw, "\n", "", -1)
  19. raw = strings.Replace(raw, "\r", "", -1)
  20. raw = strings.Replace(raw, "\t", "", -1)
  21. var ll = 64
  22. var sl = len(raw)
  23. var c = sl / ll
  24. if sl%ll > 0 {
  25. c = c + 1
  26. }
  27. var buf bytes.Buffer
  28. buf.WriteString(prefix + "\n")
  29. for i := 0; i < c; i++ {
  30. var b = i * ll
  31. var e = b + ll
  32. if e > sl {
  33. buf.WriteString(raw[b:])
  34. } else {
  35. buf.WriteString(raw[b:e])
  36. }
  37. buf.WriteString("\n")
  38. }
  39. buf.WriteString(suffix)
  40. return buf.Bytes()
  41. }