public.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2018 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package nkeys
  14. import (
  15. "crypto/rand"
  16. "io"
  17. "golang.org/x/crypto/ed25519"
  18. )
  19. // A KeyPair from a public key capable of verifying only.
  20. type pub struct {
  21. pre PrefixByte
  22. pub ed25519.PublicKey
  23. }
  24. // PublicKey will return the encoded public key associated with the KeyPair.
  25. // All KeyPairs have a public key.
  26. func (p *pub) PublicKey() (string, error) {
  27. pk, err := Encode(p.pre, p.pub)
  28. if err != nil {
  29. return "", err
  30. }
  31. return string(pk), nil
  32. }
  33. // Seed will return an error since this is not available for public key only KeyPairs.
  34. func (p *pub) Seed() ([]byte, error) {
  35. return nil, ErrPublicKeyOnly
  36. }
  37. // PrivateKey will return an error since this is not available for public key only KeyPairs.
  38. func (p *pub) PrivateKey() ([]byte, error) {
  39. return nil, ErrPublicKeyOnly
  40. }
  41. // Sign will return an error since this is not available for public key only KeyPairs.
  42. func (p *pub) Sign(input []byte) ([]byte, error) {
  43. return nil, ErrCannotSign
  44. }
  45. // Verify will verify the input against a signature utilizing the public key.
  46. func (p *pub) Verify(input []byte, sig []byte) error {
  47. if !ed25519.Verify(p.pub, input, sig) {
  48. return ErrInvalidSignature
  49. }
  50. return nil
  51. }
  52. // Wipe will randomize the public key and erase the pre byte.
  53. func (p *pub) Wipe() {
  54. p.pre = '0'
  55. io.ReadFull(rand.Reader, p.pub)
  56. }