Merge pull request #749 from nats-io/nkeys_vendor

Vendor nkeys
This commit is contained in:
Derek Collison
2018-09-12 11:06:40 -07:00
committed by GitHub
12 changed files with 4457 additions and 0 deletions

201
vendor/github.com/nats-io/nkeys/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

75
vendor/github.com/nats-io/nkeys/crc16.go generated vendored Normal file
View File

@@ -0,0 +1,75 @@
// Copyright 2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nkeys
import (
"errors"
)
// An implementation of crc16 according to CCITT standards for XMODEM.
// ErrInvalidChecksum indicates a failed verification.
var ErrInvalidChecksum = errors.New("nkeys: invalid checksum")
var crc16tab = [256]uint16{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
}
// crc16 returns the 2-byte crc for the data provided.
func crc16(data []byte) uint16 {
var crc uint16
for _, b := range data {
crc = ((crc << 8) & 0xffff) ^ crc16tab[((crc>>8)^uint16(b))&0x00FF]
}
return crc
}
// validate will check the calculated crc16 checksum for data against the expected.
func validate(data []byte, expected uint16) error {
if crc16(data) != expected {
return ErrInvalidChecksum
}
return nil
}

103
vendor/github.com/nats-io/nkeys/keypair.go generated vendored Normal file
View File

@@ -0,0 +1,103 @@
// Copyright 2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nkeys
import (
"bytes"
"io"
"golang.org/x/crypto/ed25519"
)
// kp is the internal struct for a kepypair using seed.
type kp struct {
seed string
}
// createPair will create a KeyPair based on the rand entropy and a type/prefix byte. rand can be nil.
func createPair(rand io.Reader, prefix PrefixByte) (KeyPair, error) {
_, privateKey, err := ed25519.GenerateKey(rand)
if err != nil {
return nil, err
}
seed, err := EncodeSeed(prefix, privateKey)
if err != nil {
return nil, err
}
return &kp{seed}, nil
}
// rawSeed will return the raw, decoded 64 byte seed.
func (pair *kp) rawSeed() ([]byte, error) {
_, raw, err := DecodeSeed(pair.seed)
return raw, err
}
// keys will return a 32 byte public key and a 64 byte private key utilizing the seed.
func (pair *kp) keys() (ed25519.PublicKey, ed25519.PrivateKey, error) {
raw, err := pair.rawSeed()
if err != nil {
return nil, nil, err
}
return ed25519.GenerateKey(bytes.NewReader(raw))
}
// Seed will return the encoded seed.
func (pair *kp) Seed() (string, error) {
return pair.seed, nil
}
// PublicKey will return the encoded public key associated with the KeyPair.
// All KeyPairs have a public key.
func (pair *kp) PublicKey() (string, error) {
public, raw, err := DecodeSeed(pair.seed)
if err != nil {
return "", err
}
pub, _, err := ed25519.GenerateKey(bytes.NewReader(raw))
if err != nil {
return "", err
}
return Encode(public, pub)
}
// PrivateKey will return the encoded private key for KeyPair.
func (pair *kp) PrivateKey() (string, error) {
_, priv, err := pair.keys()
if err != nil {
return "", err
}
return Encode(PrefixBytePrivate, priv)
}
// Sign will sign the input with KeyPair's private key.
func (pair *kp) Sign(input []byte) ([]byte, error) {
_, priv, err := pair.keys()
if err != nil {
return nil, err
}
return ed25519.Sign(priv, input), nil
}
// Verify will verify the input against a signature utilizing the public key.
func (pair *kp) Verify(input []byte, sig []byte) error {
pub, _, err := pair.keys()
if err != nil {
return err
}
if !ed25519.Verify(pub, input, sig) {
return ErrInvalidSignature
}
return nil
}

90
vendor/github.com/nats-io/nkeys/main.go generated vendored Normal file
View File

@@ -0,0 +1,90 @@
// Copyright 2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package nkeys is an Ed25519 based public-key signature system that simplifies keys and seeds
// and performs signing and verification.
package nkeys
import (
"errors"
"io"
)
// Errors
var (
ErrInvalidPrefixByte = errors.New("nkeys: invalid prefix byte")
ErrInvalidKey = errors.New("nkeys: invalid key")
ErrInvalidPublicKey = errors.New("nkeys: invalid public key")
ErrInvalidSeedLen = errors.New("nkeys: invalid seed length")
ErrInvalidSeed = errors.New("nkeys: invalid seed")
ErrInvalidEncoding = errors.New("nkeys: invalid encoded key")
ErrInvalidSignature = errors.New("nkeys: signature verification failed")
ErrCannotSign = errors.New("nkeys: can not sign, no private key available")
ErrPublicKeyOnly = errors.New("nkeys: no seed or private key available")
)
// KeyPair provides the central interface to nkeys.
type KeyPair interface {
Seed() (string, error)
PublicKey() (string, error)
PrivateKey() (string, error)
Sign(input []byte) ([]byte, error)
Verify(input []byte, sig []byte) error
}
// CreateUser will create an User typed KeyPair.
func CreateUser(rand io.Reader) (KeyPair, error) {
return createPair(rand, PrefixByteUser)
}
// CreateAccount will create an Account typed KeyPair.
func CreateAccount(rand io.Reader) (KeyPair, error) {
return createPair(rand, PrefixByteAccount)
}
// CreateServer will create a server typed KeyPair.
func CreateServer(rand io.Reader) (KeyPair, error) {
return createPair(rand, PrefixByteServer)
}
// CreateCluster will create a cluster typed KeyPair.
func CreateCluster(rand io.Reader) (KeyPair, error) {
return createPair(rand, PrefixByteCluster)
}
// CreateOperator will create an operator typed KeyPair.
func CreateOperator(rand io.Reader) (KeyPair, error) {
return createPair(rand, PrefixByteOperator)
}
// FromPublicKey will create a KeyPair capable fo verifying signatures.
func FromPublicKey(public string) (KeyPair, error) {
raw, err := decode(public)
if err != nil {
return nil, err
}
pre := PrefixByte(raw[0])
if err := checkValidPublicPrefixByte(pre); err != nil {
return nil, ErrInvalidPublicKey
}
return &pub{pre, raw[1:]}, nil
}
// FromSeed will create a KeyPair capable of signing and verifying signatures.
func FromSeed(seed string) (KeyPair, error) {
_, _, err := DecodeSeed(seed)
if err != nil {
return nil, err
}
return &kp{seed}, nil
}

207
vendor/github.com/nats-io/nkeys/nk/main.go generated vendored Normal file
View File

@@ -0,0 +1,207 @@
// Copyright 2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/base64"
"flag"
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/nats-io/nkeys"
)
func usage() {
log.Fatalf("Usage: nk [-gen type] [-sign file] [-verify file] [-inkey keyfile] [-pubin keyfile] [-pubout] [-e entropy]\n")
}
func main() {
var entropy = flag.String("e", "", "Entropy file, e.g. /dev/urandom")
var keyFile = flag.String("inkey", "", "Input key file (seed/private key)")
var pubFile = flag.String("pubin", "", "Public key file")
var signFile = flag.String("sign", "", "Sign <file> with -inkey <key>")
var sigFile = flag.String("sigfile", "", "Signature file")
var verifyFile = flag.String("verify", "", "Verfify <file> with -inkey <keyfile> or -pubin <public> and -sigfile <file>")
var keyType = flag.String("gen", "", "Generate key for <type>, e.g. nk -gen user")
var pubout = flag.Bool("pubout", false, "Output public key")
log.SetFlags(0)
log.SetOutput(os.Stdout)
flag.Usage = usage
flag.Parse()
// Create Key
if *keyType != "" {
createKey(*keyType, *entropy)
return
}
if *entropy != "" {
log.Fatalf("Entropy file only used when creating keys with -gen")
}
// Sign
if *signFile != "" {
sign(*signFile, *keyFile)
return
}
// Verfify
if *verifyFile != "" {
verify(*verifyFile, *keyFile, *pubFile, *sigFile)
return
}
// Show public key from seed/private
if *keyFile != "" && *pubout {
printPublicFromSeed(*keyFile)
return
}
usage()
}
func printPublicFromSeed(keyFile string) {
seed, err := ioutil.ReadFile(keyFile)
if err != nil {
log.Fatal(err)
}
kp, err := nkeys.FromSeed(string(seed))
if err != nil {
log.Fatal(err)
}
pub, _ := kp.PublicKey()
log.Printf("%s", pub)
}
func sign(fname, keyFile string) {
if keyFile == "" {
log.Fatalf("Sign requires a seed/private key via -inkey <file>")
}
seed, err := ioutil.ReadFile(keyFile)
if err != nil {
log.Fatal(err)
}
kp, err := nkeys.FromSeed(string(seed))
if err != nil {
log.Fatal(err)
}
content, err := ioutil.ReadFile(fname)
if err != nil {
log.Fatal(err)
}
sigraw, err := kp.Sign(content)
if err != nil {
log.Fatal(err)
}
log.Printf("%s", base64.RawURLEncoding.EncodeToString(sigraw))
}
func verify(fname, keyFile, pubFile, sigFile string) {
if keyFile == "" && pubFile == "" {
log.Fatalf("Verify requires a seed key via -inkey or a public key via -pubin")
}
if sigFile == "" {
log.Fatalf("Verify requires a signature via -sigfile")
}
var err error
var kp nkeys.KeyPair
if keyFile != "" {
var seed []byte
seed, err = ioutil.ReadFile(keyFile)
if err != nil {
log.Fatal(err)
}
kp, err = nkeys.FromSeed(string(seed))
} else {
// Public Key
var public []byte
public, err = ioutil.ReadFile(pubFile)
if err != nil {
log.Fatal(err)
}
kp, err = nkeys.FromPublicKey(string(public))
}
if err != nil {
log.Fatal(err)
}
content, err := ioutil.ReadFile(fname)
if err != nil {
log.Fatal(err)
}
sigEnc, err := ioutil.ReadFile(sigFile)
if err != nil {
log.Fatal(err)
}
sig, err := base64.RawURLEncoding.DecodeString(string(sigEnc))
if err != nil {
log.Fatal(err)
}
if err := kp.Verify(content, sig); err != nil {
log.Fatal(err)
}
log.Printf("verification succeeded")
}
func createKey(keyType, entropy string) {
keyType = strings.ToLower(keyType)
var kp nkeys.KeyPair
var err error
var ef io.Reader
if entropy != "" {
r, err := os.Open(entropy)
if err != nil {
log.Fatal(err)
}
ef = r
}
switch keyType {
case "user":
kp, err = nkeys.CreateUser(ef)
case "account":
kp, err = nkeys.CreateAccount(ef)
case "server":
kp, err = nkeys.CreateServer(ef)
case "cluster":
kp, err = nkeys.CreateCluster(ef)
case "operator":
kp, err = nkeys.CreateOperator(ef)
default:
log.Fatalf("Usage: nk -gen [user|account|server|cluster|operator]\n")
}
if err != nil {
log.Fatalf("Error creating %s: %v", keyType, err)
}
seed, err := kp.Seed()
if err != nil {
log.Fatal(err)
}
log.Printf("%s", seed)
}

53
vendor/github.com/nats-io/nkeys/public.go generated vendored Normal file
View File

@@ -0,0 +1,53 @@
// Copyright 2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nkeys
import (
"golang.org/x/crypto/ed25519"
)
// A KeyPair from a public key capable of verifying only.
type pub struct {
pre PrefixByte
pub ed25519.PublicKey
}
// PublicKey will return the encoded public key associated with the KeyPair.
// All KeyPairs have a public key.
func (p *pub) PublicKey() (string, error) {
return Encode(p.pre, p.pub)
}
// Seed will return an error since this is not available for public key only KeyPairs.
func (p *pub) Seed() (string, error) {
return "", ErrPublicKeyOnly
}
// PrivateKey will return an error since this is not available for public key only KeyPairs.
func (p *pub) PrivateKey() (string, error) {
return "", ErrPublicKeyOnly
}
// Sign will return an error since this is not available for public key only KeyPairs.
func (p *pub) Sign(input []byte) ([]byte, error) {
return nil, ErrCannotSign
}
// Verify will verify the input against a signature utilizing the public key.
func (p *pub) Verify(input []byte, sig []byte) error {
if !ed25519.Verify(p.pub, input, sig) {
return ErrInvalidSignature
}
return nil
}

252
vendor/github.com/nats-io/nkeys/strkey.go generated vendored Normal file
View File

@@ -0,0 +1,252 @@
// Copyright 2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nkeys
import (
"bytes"
"encoding/base32"
"encoding/binary"
"golang.org/x/crypto/ed25519"
)
// PrefixByte is a lead byte representing the type.
type PrefixByte byte
const (
//PrefixByteSeed is the version byte used for encoded NATS Seeds
PrefixByteSeed PrefixByte = 18 << 3 // Base32-encodes to 'S...'
//PrefixBytePrivate is the version byte used for encoded NATS Private keys
PrefixBytePrivate PrefixByte = 15 << 3 // Base32-encodes to 'P...'
//PrefixByteServer is the version byte used for encoded NATS Servers
PrefixByteServer PrefixByte = 13 << 3 // Base32-encodes to 'N...'
//PrefixByteCluster is the version byte used for encoded NATS Clusters
PrefixByteCluster PrefixByte = 2 << 3 // Base32-encodes to 'C...'
//PrefixByteOperator is the version byte used for encoded NATS Operators
PrefixByteOperator PrefixByte = 14 << 3 // Base32-encodes to 'O...'
//PrefixByteAccount is the version byte used for encoded NATS Accounts
PrefixByteAccount PrefixByte = 0 // Base32-encodes to 'A...'
//PrefixByteUser is the version byte used for encoded NATS Users
PrefixByteUser PrefixByte = 20 << 3 // Base32-encodes to 'U...'
)
// Set our encoding to not include padding '=='
var b32Enc = base32.StdEncoding.WithPadding(base32.NoPadding)
// Encode will encode a raw key or seed with the prefix and crc16 and then base32 encoded.
func Encode(prefix PrefixByte, src []byte) (string, error) {
if err := checkValidPrefixByte(prefix); err != nil {
return "", err
}
var raw bytes.Buffer
// write prefix byte
if err := raw.WriteByte(byte(prefix)); err != nil {
return "", err
}
// write payload
if _, err := raw.Write(src); err != nil {
return "", err
}
// Calculate and write crc16 checksum
err := binary.Write(&raw, binary.LittleEndian, crc16(raw.Bytes()))
if err != nil {
return "", err
}
return b32Enc.EncodeToString(raw.Bytes()), nil
}
// EncodeSeed will encode a raw key with the prefix and then seed prefix and crc16 and then base32 encoded.
func EncodeSeed(public PrefixByte, src []byte) (string, error) {
if err := checkValidPublicPrefixByte(public); err != nil {
return "", err
}
if len(src) != ed25519.PrivateKeySize {
return "", ErrInvalidSeedLen
}
// In order to make this human printable for both bytes, we need to do a little
// bit manipulation to setup for base32 encoding which takes 5 bits at a time.
b1 := byte(PrefixByteSeed) | (byte(public) >> 5)
b2 := (byte(public) & 31) << 3 // 31 = 00011111
var raw bytes.Buffer
raw.WriteByte(b1)
raw.WriteByte(b2)
// write payload
if _, err := raw.Write(src); err != nil {
return "", err
}
// Calculate and write crc16 checksum
err := binary.Write(&raw, binary.LittleEndian, crc16(raw.Bytes()))
if err != nil {
return "", err
}
return b32Enc.EncodeToString(raw.Bytes()), nil
}
// decode will decode the base32 string and check crc16 and the prefix for validity.
func decode(src string) ([]byte, error) {
raw, err := b32Enc.DecodeString(src)
if err != nil {
return nil, err
}
if len(raw) < 4 {
return nil, ErrInvalidEncoding
}
var crc uint16
checksum := bytes.NewReader(raw[len(raw)-2:])
if err := binary.Read(checksum, binary.LittleEndian, &crc); err != nil {
return nil, err
}
// ensure checksum is valid
if err := validate(raw[0:len(raw)-2], crc); err != nil {
return nil, err
}
return raw[0 : len(raw)-2], nil
}
// Decode will decode the base32 string and check crc16 and enforce the prefix is what is expected.
func Decode(expectedPrefix PrefixByte, src string) ([]byte, error) {
if err := checkValidPrefixByte(expectedPrefix); err != nil {
return nil, err
}
raw, err := decode(src)
if err != nil {
return nil, err
}
if prefix := PrefixByte(raw[0]); prefix != expectedPrefix {
return nil, ErrInvalidPrefixByte
}
return raw[1:], nil
}
// DecodeSeed will decode the base32 string and check crc16 and enforce the prefix is a seed
// and the subsequent type is a valid type.
func DecodeSeed(src string) (PrefixByte, []byte, error) {
raw, err := decode(src)
if err != nil {
return PrefixByteSeed, nil, err
}
// Need to do the reverse here to get back to internal representation.
b1 := raw[0] & 248 // 248 = 11111000
b2 := (raw[0]&7)<<5 | ((raw[1] & 248) >> 3) // 7 = 00000111
if PrefixByte(b1) != PrefixByteSeed {
return PrefixByteSeed, nil, ErrInvalidSeed
}
if checkValidPublicPrefixByte(PrefixByte(b2)) != nil {
return PrefixByteSeed, nil, ErrInvalidSeed
}
return PrefixByte(b2), raw[2:], nil
}
// IsValidPublicUserKey will decode and verify the string is a valid encoded Public User Key.
func IsValidPublicUserKey(src string) bool {
_, err := Decode(PrefixByteUser, src)
return err == nil
}
// IsValidPublicAccountKey will decode and verify the string is a valid encoded Public Account Key.
func IsValidPublicAccountKey(src string) bool {
_, err := Decode(PrefixByteAccount, src)
return err == nil
}
// IsValidPublicServerKey will decode and verify the string is a valid encoded Public Server Key.
func IsValidPublicServerKey(src string) bool {
_, err := Decode(PrefixByteServer, src)
return err == nil
}
// IsValidPublicClusterKey will decode and verify the string is a valid encoded Public Cluster Key.
func IsValidPublicClusterKey(src string) bool {
_, err := Decode(PrefixByteCluster, src)
return err == nil
}
// IsValidPublicOperatorKey will decode and verify the string is a valid encoded Public Operator Key.
func IsValidPublicOperatorKey(src string) bool {
_, err := Decode(PrefixByteOperator, src)
return err == nil
}
// checkValidPrefixByte returns an error if the provided value
// is not one of the defined valid prefix byte constants.
func checkValidPrefixByte(prefix PrefixByte) error {
if prefix == PrefixByteOperator {
return nil
}
if prefix == PrefixByteServer {
return nil
}
if prefix == PrefixByteCluster {
return nil
}
if prefix == PrefixByteAccount {
return nil
}
if prefix == PrefixByteUser {
return nil
}
if prefix == PrefixByteSeed {
return nil
}
if prefix == PrefixBytePrivate {
return nil
}
return ErrInvalidPrefixByte
}
// checkValidPublicPrefixByte returns an error if the provided value
// is not one of the public defined valid prefix byte constants.
func checkValidPublicPrefixByte(prefix PrefixByte) error {
if prefix == PrefixByteServer {
return nil
}
if prefix == PrefixByteCluster {
return nil
}
if prefix == PrefixByteOperator {
return nil
}
if prefix == PrefixByteAccount {
return nil
}
if prefix == PrefixByteUser {
return nil
}
return ErrInvalidPrefixByte
}

27
vendor/golang.org/x/crypto/ed25519/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,27 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

217
vendor/golang.org/x/crypto/ed25519/ed25519.go generated vendored Normal file
View File

@@ -0,0 +1,217 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ed25519 implements the Ed25519 signature algorithm. See
// https://ed25519.cr.yp.to/.
//
// These functions are also compatible with the “Ed25519” function defined in
// RFC 8032. However, unlike RFC 8032's formulation, this package's private key
// representation includes a public key suffix to make multiple signing
// operations with the same key more efficient. This package refers to the RFC
// 8032 private key as the “seed”.
package ed25519
// This code is a port of the public domain, “ref10” implementation of ed25519
// from SUPERCOP.
import (
"bytes"
"crypto"
cryptorand "crypto/rand"
"crypto/sha512"
"errors"
"io"
"strconv"
"golang.org/x/crypto/ed25519/internal/edwards25519"
)
const (
// PublicKeySize is the size, in bytes, of public keys as used in this package.
PublicKeySize = 32
// PrivateKeySize is the size, in bytes, of private keys as used in this package.
PrivateKeySize = 64
// SignatureSize is the size, in bytes, of signatures generated and verified by this package.
SignatureSize = 64
// SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
SeedSize = 32
)
// PublicKey is the type of Ed25519 public keys.
type PublicKey []byte
// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.
type PrivateKey []byte
// Public returns the PublicKey corresponding to priv.
func (priv PrivateKey) Public() crypto.PublicKey {
publicKey := make([]byte, PublicKeySize)
copy(publicKey, priv[32:])
return PublicKey(publicKey)
}
// Seed returns the private key seed corresponding to priv. It is provided for
// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds
// in this package.
func (priv PrivateKey) Seed() []byte {
seed := make([]byte, SeedSize)
copy(seed, priv[:32])
return seed
}
// Sign signs the given message with priv.
// Ed25519 performs two passes over messages to be signed and therefore cannot
// handle pre-hashed messages. Thus opts.HashFunc() must return zero to
// indicate the message hasn't been hashed. This can be achieved by passing
// crypto.Hash(0) as the value for opts.
func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) {
if opts.HashFunc() != crypto.Hash(0) {
return nil, errors.New("ed25519: cannot sign hashed message")
}
return Sign(priv, message), nil
}
// GenerateKey generates a public/private key pair using entropy from rand.
// If rand is nil, crypto/rand.Reader will be used.
func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) {
if rand == nil {
rand = cryptorand.Reader
}
seed := make([]byte, SeedSize)
if _, err := io.ReadFull(rand, seed); err != nil {
return nil, nil, err
}
privateKey := NewKeyFromSeed(seed)
publicKey := make([]byte, PublicKeySize)
copy(publicKey, privateKey[32:])
return publicKey, privateKey, nil
}
// NewKeyFromSeed calculates a private key from a seed. It will panic if
// len(seed) is not SeedSize. This function is provided for interoperability
// with RFC 8032. RFC 8032's private keys correspond to seeds in this
// package.
func NewKeyFromSeed(seed []byte) PrivateKey {
if l := len(seed); l != SeedSize {
panic("ed25519: bad seed length: " + strconv.Itoa(l))
}
digest := sha512.Sum512(seed)
digest[0] &= 248
digest[31] &= 127
digest[31] |= 64
var A edwards25519.ExtendedGroupElement
var hBytes [32]byte
copy(hBytes[:], digest[:])
edwards25519.GeScalarMultBase(&A, &hBytes)
var publicKeyBytes [32]byte
A.ToBytes(&publicKeyBytes)
privateKey := make([]byte, PrivateKeySize)
copy(privateKey, seed)
copy(privateKey[32:], publicKeyBytes[:])
return privateKey
}
// Sign signs the message with privateKey and returns a signature. It will
// panic if len(privateKey) is not PrivateKeySize.
func Sign(privateKey PrivateKey, message []byte) []byte {
if l := len(privateKey); l != PrivateKeySize {
panic("ed25519: bad private key length: " + strconv.Itoa(l))
}
h := sha512.New()
h.Write(privateKey[:32])
var digest1, messageDigest, hramDigest [64]byte
var expandedSecretKey [32]byte
h.Sum(digest1[:0])
copy(expandedSecretKey[:], digest1[:])
expandedSecretKey[0] &= 248
expandedSecretKey[31] &= 63
expandedSecretKey[31] |= 64
h.Reset()
h.Write(digest1[32:])
h.Write(message)
h.Sum(messageDigest[:0])
var messageDigestReduced [32]byte
edwards25519.ScReduce(&messageDigestReduced, &messageDigest)
var R edwards25519.ExtendedGroupElement
edwards25519.GeScalarMultBase(&R, &messageDigestReduced)
var encodedR [32]byte
R.ToBytes(&encodedR)
h.Reset()
h.Write(encodedR[:])
h.Write(privateKey[32:])
h.Write(message)
h.Sum(hramDigest[:0])
var hramDigestReduced [32]byte
edwards25519.ScReduce(&hramDigestReduced, &hramDigest)
var s [32]byte
edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced)
signature := make([]byte, SignatureSize)
copy(signature[:], encodedR[:])
copy(signature[32:], s[:])
return signature
}
// Verify reports whether sig is a valid signature of message by publicKey. It
// will panic if len(publicKey) is not PublicKeySize.
func Verify(publicKey PublicKey, message, sig []byte) bool {
if l := len(publicKey); l != PublicKeySize {
panic("ed25519: bad public key length: " + strconv.Itoa(l))
}
if len(sig) != SignatureSize || sig[63]&224 != 0 {
return false
}
var A edwards25519.ExtendedGroupElement
var publicKeyBytes [32]byte
copy(publicKeyBytes[:], publicKey)
if !A.FromBytes(&publicKeyBytes) {
return false
}
edwards25519.FeNeg(&A.X, &A.X)
edwards25519.FeNeg(&A.T, &A.T)
h := sha512.New()
h.Write(sig[:32])
h.Write(publicKey[:])
h.Write(message)
var digest [64]byte
h.Sum(digest[:0])
var hReduced [32]byte
edwards25519.ScReduce(&hReduced, &digest)
var R edwards25519.ProjectiveGroupElement
var s [32]byte
copy(s[:], sig[32:])
// https://tools.ietf.org/html/rfc8032#section-5.1.7 requires that s be in
// the range [0, order) in order to prevent signature malleability.
if !edwards25519.ScMinimal(&s) {
return false
}
edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &s)
var checkR [32]byte
R.ToBytes(&checkR)
return bytes.Equal(sig[:32], checkR[:])
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

17
vendor/manifest vendored
View File

@@ -1,6 +1,14 @@
{
"version": 0,
"dependencies": [
{
"importpath": "github.com/nats-io/nkeys",
"repository": "https://github.com/nats-io/nkeys",
"vcs": "git",
"revision": "b1c20ce69b6a01afa42403ea6f7b408d6cbc8e4e",
"branch": "master",
"notests": true
},
{
"importpath": "github.com/nats-io/nuid",
"repository": "https://github.com/nats-io/nuid",
@@ -27,6 +35,15 @@
"path": "/blowfish",
"notests": true
},
{
"importpath": "golang.org/x/crypto/ed25519",
"repository": "https://go.googlesource.com/crypto",
"vcs": "git",
"revision": "0e37d006457bf46f9e6692014ba72ef82c33022c",
"branch": "master",
"path": "/ed25519",
"notests": true
},
{
"importpath": "golang.org/x/sys/windows",
"repository": "https://go.googlesource.com/sys",