public.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. }
  57. func (p *pub) Seal(input []byte, recipient string) ([]byte, error) {
  58. if p.pre == PrefixByteCurve {
  59. return nil, ErrCannotSeal
  60. }
  61. return nil, ErrInvalidNKeyOperation
  62. }
  63. func (p *pub) SealWithRand(input []byte, _recipient string, rr io.Reader) ([]byte, error) {
  64. if p.pre == PrefixByteCurve {
  65. return nil, ErrCannotSeal
  66. }
  67. return nil, ErrInvalidNKeyOperation
  68. }
  69. func (p *pub) Open(input []byte, sender string) ([]byte, error) {
  70. if p.pre == PrefixByteCurve {
  71. return nil, ErrCannotOpen
  72. }
  73. return nil, ErrInvalidNKeyOperation
  74. }