hippo

package module
v0.0.0-...-8cde3c3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2018 License: MIT Imports: 16 Imported by: 2

README

HippoCrypto Cartoon of a hippopotamus.

HippoCrypto wraps basic cryptography functions for digital signatures and encryption from Go stdlib and other packages. It also provides a minimal chained certificate for delegated authentication.

Why?

  • Transparent algorithm selection and uniform interfaces.
  • Simple tokens built on linked certificates.

Please remember that cryptography is complex! There are many subtle issues. Although this API aims to make these functions easy to use, you must still understand the implications and guarantees before doing so. For example, not all of the encryption algorithms included here assure data integrity on their own, let alone authenticity.

Build Status GoDoc

Wrappers

The core of HippoCrypto are thin wrappers for basic cryptographic functions and common algorithms. In particular, there are uniform interfaces for digital signatures as well as encryption. The standard Go APIs for specific implementations of these tasks are generally all similar but not unified, so Hippo smooths them over. In doing so it provides a very easy way for programs to transparently parameterize algorithm selection.

Where possible, the wrappers' key serialization functions are designed to work with imports to and exports from the HTML5 WebCrypto JavaScript API, though they do not directly import/export JWKs.

Digital Signatures

Currently included digital signatures algorithms are ECDSA-P256 and Ed25519. Other algorithms and options can be easily incorporated though. Please make a suggestion or pull request if you need something else, but your programs can also easily wrap and register other algorithms outside the library.

Encryption

Hippo currently includes wrappers for 2048bit RSA OAEP and 256 bit AES CBC and GCM modes. Again, other algorithms and parameters can be easily added to the library or as plug-ins from external code.

Certificates

In addition, HippoCrypto provides a simple digital certificate format built on its underlying digital signatures wrapper. These certificates are much like JSON Web Tokens (JWT), except they readily support chaining: A certificate is a list of declarations (identity and claims) each signed by some entity in turn supported by its own declaration, presumably leading back to some root authority known and trusted by the program testing the certificate. In this sense they are also similar to X509 certificates, but much simpler and particularly easier to work with in a Web/JavaScript environment.

Examples

A few examples follow.

Signatures

Here is a trivial example of generating a key, signing some data, marshaling a key to be shared, and then verifying the data from the unmarshaled key:

	// Generate a key
	sender, err := Generate("ed25519")
	if err != nil { panic(err) }

	// Sign some data with that key
	data := []byte("Four score and seven years ago")	
	signature, err := sender.Sign(data)
	if err != nil { panic(err) }

	// Marshal the key to JSON to share it somehow
	sharedkey, err := json.Marshal(sender.PublicKey())
	if err != nil { panic(err) }

	// Receive a shared key as JSON and unmarshal
	publickey := PublicKey{}
	err = json.Unmarshal(sharedkey, &publickey)
	if err != nil { panic(err) }

	// Turn the key into an actionable verifier (before this it's just
	// data, the Verifier is an object with specific crypto methods)
	verifier, err := NewVerifier(publickey)
	if err != nil { panic(err) }

	// Verify that this key did sign the data
	err = verifier.Verify(data, signature)
	if err != nil { panic(err) }

	fmt.Printf("Verified")
Encryption

This is a quick example of generating an RSA key, marshaling the public key to JSON, encrypting data with it, and then decrypting from the original key.

	data := []byte("Four score and seven years ago")

	// Create a keypair
	keys, err := GeneratePKCipher("rsa-oaep-2048")
	if err != nil { panic(err) }

	// Marshal the public key out to JSON
	publicjson, err := json.Marshal(keys.PublicKey())
	if err != nil { panic(err) }

	// Read the public key back in
	public := PublicKey{}
	err = json.Unmarshal(publicjson, &public)
	if err != nil { panic(err) }

	encrypter, err := NewEncrypter(public)
	if err != nil { panic(err) }

	// Encrypt the data from the unmarshaled public key
	ciphertext, err := encrypter.Encrypt(data)
	if err != nil { panic(err) }

	// Decrypt the data with the original private key
	cleartext, err := keys.Decrypt(ciphertext)
	if err != nil { panic(err) }

	if bytes.Compare(cleartext, data) != 0 {
		panic("Data mismatch!")
	}

	fmt.Println("Received")
Certificates

This example shows a root CA generating a valid certificate for an intermediary CA, which generates a valid certificate for a secondary CA, which in turn generates a valid certificate for a user that is verified against a pool including the root CA:

	// Create some keys
	user, err := Generate(AlgorithmEd25519)
	if err != nil { panic(err) }

	ca1, err := Generate(AlgorithmECDSA_P256)
	if err != nil { panic(err) }

	ca2, err := Generate(AlgorithmECDSA_P256)
	if err != nil { panic(err) }

	root, err := Generate(AlgorithmEd25519)
	if err != nil { panic(err) }

	// Root makes a certificate for CA1
	ca1_id := NewTestament("ca1", ca1.PublicKey(), Claims{"CertificateAuthority": true})

	ca1_cert, err := ca1_id.Sign("root", root)
	if err != nil { panic(err) }

	// CA1 makes a certificate for CA2
	ca2_id := NewTestament("ca2", ca2.PublicKey(), Claims{"CertificateAuthority": true})

	ca2_cert, err := ca2_id.Sign("ca1", ca1)
	if err != nil { panic(err) }

	// CA2 makes a certificate for the user
	user_id := NewTestament("Joe", user.PublicKey(), nil)

	user_cert, err := user_id.Sign("ca2", ca2)
	if err != nil { panic(err) }

	// Put them together to make a certificate
	out_certificate := &Certificate{Chain{user_cert, ca2_cert, ca1_cert}}

	// Marshal to JSON to share the certificate somehow
	bytes, err := out_certificate.ToBytes()
	if err != nil { panic(err) }

	// Unmarshal the shared certificate
	var in_certificate Certificate
	err = json.Unmarshal(bytes, &in_certificate)
	if err != nil { panic(err) }

	// Create a pool comprised of the root
	pool := NewVerifierPool()

	err = pool.Add("root", root)
	if err != nil { panic(err) }

	// Verify the certificate against the pool
	err = pool.Verify(&in_certificate)
	if err != nil { panic(err) }

	fmt.Println("Verified")

Utilities

Two command line utilities are also provided for convenience:

  • cmd/mkkey generates Hippo-formatted keys in JSON.
  • cmd/mkcert generates Hippo certificates in JSON.
mkkey

The mkkey utility has two optional parameters:

  • -algorithm <string> --- Algorithm to use. (default "ed25519")
  • -prefix <string> --- Key filename prefix to use. (default "key")

It generates a key of the given algorithm in the files prefix.public and prefix.private, e.g.:

% ./bin/mkkey -prefix=root
% cat root.public
{"Algorithm":"ed25519","Public":"VSbwTnF7vyK3QpQrVZ0p2KQGuP1XUl6fTUxcKMbzu0o="}
% cat root.private
{"Algorithm":"ed25519","Private":"Z9H_z4y9wq4K_7fg8MqPH6Pzt7nBul2N0E7DCAnbqptVJvBOcXu_IrdClCtVnSnYpAa4_VdSXp9NTFwoxvO7Sg=="}
mkcert

The mkcert utility has several options:

  • -chain <string> --- Add chained certificates from given file (optional); may be invoked multiple times.
  • -claim <value> --- Add claim "key,value" (optional); may be invoked multiple times. (default {})
  • -subjectid <string> --- Subject ID (optional).
  • -subjectkey <string> --- Subject public key (required).
  • -signerid <string> --- Signer ID (optional).
  • -signingkey <string> --- Signing private key (required).
  • -out <string> --- Output certificate (required).

It takes the subject's public key (its provable identity), signs it with the given signing key (the CA's key), and generates a certificate, e.g.:

% ./bin/mkcert -subjectid "user" -subjectkey user.public -signerid="root" -signingkey root.private -out user.cert
% cat user.cert
{"Declarations":[{"Claim":"eyJJRCI6IiIsIlN1YmplY3QiOnsiSUQiOiJ0amtvcGVuYSIsIlB1YmxpY0tleSI6eyJBbGdvcml0aG0iOiJlY2RzYS1wMjU2IiwiUHVibGljIjp7IlgiOiJkNUN3STFFdWJVdUxHWjNYd19EeklFRmlnSFY1U1otM28yUERnSUVxNFBFIiwiWSI6InpKVm5GeDdKQ0loMlhQTmhNNHZZN0RSeTRmWWljSFVPNGc2N3F6YmlpajQifX19LCJDbGFpbXMiOnt9LCJFeHBpcmVzIjoiIn0=","Signer":"root","Signature":"+jw89RLk3Wg9zfhANhfffN3/1yIWmvkPsYyQGc/NDckaF520th0b8iX1mZC6/Si4d3tHDJA3LJZ2Co4yT0nnBA=="}]}

The other options enable the subject and signer to be given string identifiers, arbitrary key/value claims to be made about the subject, and a chain of additional certificates to be attached supporting the CA's validity.

Detailed documentation is available in the GoDocs.

License

HippoCrypto is provided under the open source MIT license:

The MIT License (MIT)

Copyright (c) 2016, 2017 Bellerophon Mobile

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Icon

The hippopotamus cartoon icon is by Harry Cox/AnimalsClipArt.com, released under CC-BY-4.0.

Documentation

Overview

Package hippo provides a uniform encapsulation of basic cryptographic functions and a simple chained certificate.

Index

Constants

View Source
const AlgorithmAES_256_CBC = "aes-256-cbc"

AlgorithmAES_256_CBC is a constant string identifying the AES algorithm with 256 bit key and cipher block chaining mode.

View Source
const AlgorithmAES_256_GCM = "aes-256-gcm"

AlgorithmAES_256_CBC is a constant string identifying the AES algorithm with 256 bit key and Galois/counter mode.

View Source
const AlgorithmECDSA_P256 = "ecdsa-p256"

AlgorithmECDSA_P256 is a constant string identifying the ECDSA algorithm using the P-256 curve.

View Source
const AlgorithmEd25519 = "ed25519"

AlgorithmEd25519 is a constant string identifying the ed25519 algorithm.

View Source
const AlgorithmRSA_OAEP_2048 = "rsa-oaep-2048"

AlgorithmRSA_OAEP is a constant string identifying the RSA algorithm with optimal asymmetric encryption padding.

Variables

View Source
var ErrBrokenCertificateChain = fmt.Errorf("Broken certificate chain")

ErrBrokenCertificateChain is returned when a declaration's subject doesn't match the previous declarations signer when verifying.

View Source
var ErrInvalidCertificate = fmt.Errorf("Invalid certificate")

ErrInvalidCertificate is returned when attempting to verify an invalid certificate.

View Source
var ErrInvalidPrivateKeyType = fmt.Errorf("Invalid private key type")

ErrInvalidPrivateKeyType is returned when setting an invalid private key to Credentials or Ciphers.

View Source
var ErrInvalidPublicKeyType = fmt.Errorf("Invalid public key type")

ErrInvalidPublicKeyType is returned when setting an invalid public key to Credentials or Ciphers.

View Source
var ErrNoDeclarations = fmt.Errorf("No declarations in certificate")

ErrNoDeclarations is returned when loading an empty certificate.

View Source
var ErrNoVerifier = fmt.Errorf("Invalid verifier")

ErrNoVerifier is returned when no verifier with a specified ID exists in a pool.

View Source
var ErrNotCertificateAuthority = fmt.Errorf("Chained declaration does not confirm certificate authority")

ErrNotCertificateAuthority is returned when a chained declaration does not have the "CertificateAuthority" claim.

View Source
var ErrNotDecrypter = fmt.Errorf("Not a decrypter")

ErrNotDecrypter is returned when attempting to decrypt data without a public key, or if a PKCipher does not implement encryption.

View Source
var ErrNotEncrypter = fmt.Errorf("Not an encrypter")

ErrNotEncrypter is returned when attempting to encrypt data without a private key, or if a PKCipher does not implement encryption.

View Source
var ErrNotSigner = fmt.Errorf("Not a signer")

ErrNotSigner is returned when attempting to sign data without a private key or if the algorithm interface does not implement signing.

View Source
var ErrNotVerifier = fmt.Errorf("Not a verifier")

ErrNotVerifier is returned when attempting to verify data without a public key or if the algorithm interface does not implement verification.

View Source
var ErrPreviousAlgorithm = fmt.Errorf("Previous algorithm registration")

ErrPreviousAlgorithm is returned by Register calls when registering a duplicate Credentialier or Cipherer.

View Source
var ErrPreviousVerifier = fmt.Errorf("Verifier exists")

ErrPreviousVerifier is returned when adding an already added verifier to a pool.

View Source
var ErrUnknownAlgorithm = fmt.Errorf("Unknown algorithm")

ErrUnknownAlgorithm is returned when attempting to generate or load keys from an unregistered algorithm.

View Source
var ErrUnrecognizedCertificate = fmt.Errorf("Unrecognized certificate")

ErrUnrecognizedCertificate is returned when none of the signers in a certificate are in a verifier pool.

View Source
var ErrUnsupportedMode = fmt.Errorf("Unknown mode")

ErrUnsupportedMode is returned if a key is given that indicates a mode with no registered implementation.

View Source
var ErrUnverifiedSignature = fmt.Errorf("Unverified signature")

ErrUnverifiedSignature is returned when a signature fails validation.

Functions

func RegisterCredentialer

func RegisterCredentialer(credentialer Credentialer) error

RegisterCredentialer makes a Credentialer for a specific algorithm available through the uniform interface.

func RegisterPKCipherer

func RegisterPKCipherer(cipherer PKCipherer) error

RegisterPKCipherer makes a PKCipherer for a specific algorithm available through the uniform interface.

func RegisterSKCipherer

func RegisterSKCipherer(cipherer SKCipherer) error

RegisterSKCipherer makes a SKCipherer for a specific algorithm available through the uniform interface.

Types

type AESCipher

type AESCipher struct {
	Algorithm string
	Bits      int
	Mode      AESMode
	Key       []byte
}

An AESCipher is an actionable secret key.

func (*AESCipher) Decrypt

func (x *AESCipher) Decrypt(data []byte) ([]byte, error)

Decrypt takes cipherdata and produces plaindata. N.B. that depending on the mode an invalid key or data may or may not generate an error.

func (*AESCipher) Encrypt

func (x *AESCipher) Encrypt(data []byte) ([]byte, error)

Encrypt produces cipherdata for the given plaindata.

func (*AESCipher) SecretKey

func (x *AESCipher) SecretKey() PrivateKey

SecretKey returns a JSON Base64-URL encoded marshaling of the cipher's secret key.

func (*AESCipher) SetKey

func (x *AESCipher) SetKey(key PrivateKey) error

SetKey sets the cipher's secret key from the given PrivateKey containing JSON Base64-URL encoded data.

type AESMode

type AESMode int

AESMode captures the operational mode of the cipher.

const (
	CBC AESMode = iota // Cipher block chaining mode.
	GCM                // Galois/counter mode.
)

type Certificate

type Certificate struct {
	Declarations Chain // All of the encoded and signed Testaments contained in this certificate.
}

Certificate is simply a Chain. It is encapsulated in the struct to ease some handling for serialization and other tasks, as well as possible future expansion to include other data.

func CertificateFromBytes

func CertificateFromBytes(buf []byte) (*Certificate, error)

CertificateFromBytes parses a Certificate from the given bytes. It does not verify the certificate.

func CertificateFromFile

func CertificateFromFile(fn string) (*Certificate, error)

CertificateFromFile loads and parses a Certificate from the given file. It does not verify the certificate.

func (*Certificate) ToBytes

func (c *Certificate) ToBytes() ([]byte, error)

ToBytes serializes the Certificate to bytes as JSON.

func (*Certificate) ToFile

func (c *Certificate) ToFile(fn string) error

ToFile serializes the Certificate to the given file as JSON.

type Chain

type Chain []*Declaration

Chain is a list of Declarations

type Claims

type Claims map[string]interface{}

Claims capture arbitrary key/value data.

type Credentialer

type Credentialer interface {
	// Algorithm returns the label identifying the algorithm and
	// parameterization of this credentialier.
	Algorithm() string

	// Generate creates a new set of Credentials.
	Generate() (Credentials, error)

	// New wraps the given keys as Credentials.
	New(public PublicKey, private PrivateKey) (Credentials, error)

	// NewVerifier wraps the given PublicKey as Credentials.
	NewVerifier(key PublicKey) (Credentials, error)

	// NewSigner wraps the given PublicKey as Credentials.
	NewSigner(key PrivateKey) (Credentials, error)
}

A Credentialer encapsulates key generation for a specific digital signature algorithm and parameterization.

type Credentials

type Credentials interface {
	Verifier
	Signer

	// SetPrivateKey sets the credential's public key from the given
	// PrivateKey containing JSON Base64-URL encoded data.
	SetPrivateKey(privatekey PrivateKey) error

	// SetPublicKey sets the credential's public key from the given
	// PublicKey containing JSON Base64-URL encoded data.
	SetPublicKey(publickey PublicKey) error
}

Credentials contain matched keys to both sign and verify data.

func GenerateCredentials

func GenerateCredentials(algorithm string) (Credentials, error)

GenerateCredentials produces Credentials with new random keys following the given algorithm.

func NewCredentials

func NewCredentials(public PublicKey, private PrivateKey) (Credentials, error)

NewCredentials creates Credentials wrapping the given public and private key. These must indicate the same algorithm but otherwise no test is made to confirm that they correspond to each other.

func NewSigner

func NewSigner(key PrivateKey) (Credentials, error)

NewSigner wraps the given private key in Credentials for use.

func NewVerifier

func NewVerifier(key PublicKey) (Credentials, error)

NewVerifier wraps the given public key in Credentials for use.

type Declaration

type Declaration struct {
	Claim     string    // Encoded Testament.
	Signer    string    // Optional identifier of the signer.
	Signature Signature // Cryptographic signature of the Claim.
}

Declaration binds an encoded Testament to a signature.

type Decrypter

type Decrypter interface {

	// PrivateKey returns a JSON Base64-URL encoded marshaling of the
	// Decrypter's private key.
	PrivateKey() PrivateKey

	// Decrypt takes cipherdata and produces plaindata.  N.B.: In
	// general the absence of an error does NOT indicate that the data
	// is valid.  Under a public key algorithm this question doesn't
	// even make sense in terms of an attack.  A separate mechanism must
	// be applied to assure integrity and authenticity.  Then note that
	// implementing such a mechanism is not as simple as signing either
	// the plaindata or cipherdata alone.
	Decrypt(data []byte) ([]byte, error)
}

Decrypter wraps a private key and decrypt datas.

type ECDSACredentials

type ECDSACredentials struct {
	Algorithm string
	Curve     elliptic.Curve
	Public    *ecdsa.PublicKey
	Private   *ecdsa.PrivateKey
}

ECDSACredentials are an actionable ECDSA public/private key or matched pair.

func (*ECDSACredentials) PrivateKey

func (x *ECDSACredentials) PrivateKey() PrivateKey

PrivateKey returns a JSON Base64-URL encoded marshaling of the credential's private key.

func (*ECDSACredentials) PublicKey

func (x *ECDSACredentials) PublicKey() PublicKey

PublicKey returns a JSON Base64-URL encoded marshaling of the credential's public key.

func (*ECDSACredentials) SetPrivateKey

func (x *ECDSACredentials) SetPrivateKey(privatekey PrivateKey) error

SetPrivateKey sets the credential's public key from the given PrivateKey containing JSON Base64-URL encoded data.

func (*ECDSACredentials) SetPublicKey

func (x *ECDSACredentials) SetPublicKey(publickey PublicKey) error

SetPublicKey sets the credential's public key from the given PublicKey containing JSON Base64-URL encoded data.

func (*ECDSACredentials) Sign

func (x *ECDSACredentials) Sign(data []byte) (Signature, error)

Sign produces a signature for the given data.

func (*ECDSACredentials) Verify

func (x *ECDSACredentials) Verify(data []byte, signature Signature) error

Verify confirms that the given signature was produced from the given data using the private key associated with this credential's public key.

type Ed25519Credentials

type Ed25519Credentials struct {
	Private []byte
	Public  []byte
}

Ed25519Credentials are an actionable Ed25519 public/private key or matched pair.

func (*Ed25519Credentials) PrivateKey

func (x *Ed25519Credentials) PrivateKey() PrivateKey

PrivateKey returns a JSON Base64-URL encoded marshaling of the credential's private key.

func (*Ed25519Credentials) PublicKey

func (x *Ed25519Credentials) PublicKey() PublicKey

PublicKey returns a JSON Base64-URL encoded marshaling of the credential's public key.

func (*Ed25519Credentials) SetPrivateKey

func (x *Ed25519Credentials) SetPrivateKey(privatekey PrivateKey) error

SetPrivateKey sets the credential's public key from the given PrivateKey containing JSON Base64-URL encoded data.

func (*Ed25519Credentials) SetPublicKey

func (x *Ed25519Credentials) SetPublicKey(publickey PublicKey) error

SetPublicKey sets the credential's public key from the given PublicKey containing JSON Base64-URL encoded data.

func (*Ed25519Credentials) Sign

func (x *Ed25519Credentials) Sign(data []byte) (Signature, error)

Sign produces a signature for the given data.

func (*Ed25519Credentials) Verify

func (x *Ed25519Credentials) Verify(data []byte, signature Signature) error

Verify confirms that the given signature was produced from the given data using the private key associated with this credential's public key.

type Encrypter

type Encrypter interface {

	// PublicKey returns a JSON Base64-URL encoded marshaling of the
	// Encrypter's public key.
	PublicKey() PublicKey

	// Encrypt produces cipherdata for the given plaindata.
	Encrypt(data []byte) ([]byte, error)
}

Encrypter wraps a public key and encrypts data.

type PKCipher

type PKCipher interface {
	Encrypter
	Decrypter

	// SetPrivateKey sets the PKCipher's public key from the given
	// PrivateKey containing JSON Base64-URL encoded data.
	SetPrivateKey(privatekey PrivateKey) error

	// SetPublicKey sets the PKCipher's public key from the given
	// PublicKey containing JSON Base64-URL encoded data.
	SetPublicKey(publickey PublicKey) error
}

A PKCipher encapsulates a public key (asymmetric) encryption algorithm, parameterization, and matched keys to encrypt and decrypt data.

func GeneratePKCipher

func GeneratePKCipher(algorithm string) (PKCipher, error)

GeneratePKCipher produces a PKCipher with new random keys following the given algorithm.

func NewDecrypter

func NewDecrypter(key PrivateKey) (PKCipher, error)

NewDecrypter wraps the given private key in a PKCipher for use.

func NewEncrypter

func NewEncrypter(key PublicKey) (PKCipher, error)

NewEncrypter wraps the given public key in a PKCipher for use.

func NewPKCipher

func NewPKCipher(public PublicKey, private PrivateKey) (PKCipher, error)

NewPKCipher creates a PKCipher wrapping the given public and private key. These must indicate the same algorithm but otherwise no test is made to confirm that they correspond to each other.

type PKCipherer

type PKCipherer interface {
	// Algorithm returns the label identifying the algorithm and
	// parameterization of this PKCipherer.
	Algorithm() string

	// Generate creates a new PKCipher.
	Generate() (PKCipher, error)

	// New wraps the given keys as a PKCipher.
	New(public PublicKey, private PrivateKey) (PKCipher, error)

	// NewEncrypter wraps the given PublicKey as a PKCipher.
	NewEncrypter(key PublicKey) (PKCipher, error)

	// NewDecrypter wraps the given PublicKey as a PKCipher.
	NewDecrypter(key PrivateKey) (PKCipher, error)
}

A PKCipherer encapsulates key generation for a specific public key encryption algorithm and parameterization.

type PrivateKey

type PrivateKey struct {
	Algorithm string
	Private   interface{}
}

PrivateKey is a structure for importing and exporting private keys. Signing is actually done with Credentials or a Signer. Encryption is done with a Cipher or an Encrypter. The format of the data is defined by the algorithm implementation but should be generic JSON such that it may be parsed directly, i.e., without special knowledge of the value of Private as might be necessary to instantiate a specific class, etc..

func PrivateKeyFromBytes

func PrivateKeyFromBytes(buf []byte) (*PrivateKey, error)

PrivateKeyFromBytes unmarshals a key from the given byte array.

func PrivateKeyFromFile

func PrivateKeyFromFile(fn string) (*PrivateKey, error)

PrivateKeyFromFile reads the entirety of the given file and attempts to parse it into a PrivateKey.

func (PrivateKey) ToBytes

func (k PrivateKey) ToBytes() ([]byte, error)

ToBytes marshals the key to a byte array.

func (PrivateKey) ToFile

func (k PrivateKey) ToFile(fn string) error

ToFile serializes the PrivateKey to the given file as JSON.

type PublicKey

type PublicKey struct {
	Algorithm string
	Public    interface{}
}

PublicKey is a structure for importing and exporting public keys. Verification is actually done with Credentials or a Verifier. Decryption is actually done with a Cipher or a Decrypter. The format of the data is defined by the algorithm implementation but should be generic JSON such that it may be parsed directly, i.e., without special knowledge of the value of Public as might be necessary to instantiate a specific class, etc..

func PublicKeyFromBytes

func PublicKeyFromBytes(buf []byte) (*PublicKey, error)

PublicKeyFromBytes unmarshals a key from the given byte array.

func PublicKeyFromFile

func PublicKeyFromFile(fn string) (*PublicKey, error)

PublicKeyFromFile reads the entirety of the given file and attempts to parse it into a PublicKey.

func (PublicKey) ToBytes

func (k PublicKey) ToBytes() ([]byte, error)

ToBytes marshals the key to a byte array.

func (PublicKey) ToFile

func (k PublicKey) ToFile(fn string) error

ToFile serializes the PublicKey to the given file as JSON.

type RSAOAEPCipher

type RSAOAEPCipher struct {
	Algorithm string
	Bits      int
	Public    *rsa.PublicKey
	Private   *rsa.PrivateKey
}

An RSAOAEPCipher is an actionable RSA public/private key or a matched pair.

func (*RSAOAEPCipher) Decrypt

func (x *RSAOAEPCipher) Decrypt(data []byte) ([]byte, error)

Decrypt takes cipherdata and produces plaindata.

func (*RSAOAEPCipher) Encrypt

func (x *RSAOAEPCipher) Encrypt(data []byte) ([]byte, error)

Encrypt produces cipherdata for the given plaindata.

func (*RSAOAEPCipher) PrivateKey

func (x *RSAOAEPCipher) PrivateKey() PrivateKey

PrivateKey returns a JSON Base64-URL encoded marshaling of the cipher's private key.

func (*RSAOAEPCipher) PublicKey

func (x *RSAOAEPCipher) PublicKey() PublicKey

PublicKey returns a JSON Base64-URL encoded marshaling of the cipher's public key.

func (*RSAOAEPCipher) SetPrivateKey

func (x *RSAOAEPCipher) SetPrivateKey(privatekey PrivateKey) error

SetPrivateKey sets the cipher's public key from the given PrivateKey containing JSON Base64-URL encoded data.

func (*RSAOAEPCipher) SetPublicKey

func (x *RSAOAEPCipher) SetPublicKey(publickey PublicKey) error

SetPublicKey sets the cipher's public key from the given PublicKey containing JSON Base64-URL encoded data.

type SKCipher

type SKCipher interface {

	// Key returns a JSON Base64-URL encoded marshaling of the
	// SKCipher's secret key.
	SecretKey() PrivateKey

	// SetKey sets the SKCipher's secret key from the given PrivateKey
	// containing JSON Base64-URL encoded data.
	SetKey(key PrivateKey) error

	// Encrypt produces cipherdata for the given plaindata.
	Encrypt(data []byte) ([]byte, error)

	// Decrypt takes cipherdata and produces plaindata.  N.B.: In
	// general the absence of an error does NOT indicate that the data
	// is valid.  A separate mechanism must be applied to assure
	// integrity and authenticity.  Then note that implementing such a
	// mechanism is not as simple as signing either the plaindata or
	// cipherdata alone.
	Decrypt(data []byte) ([]byte, error)
}

An SKCipher encapsulates a secret key (symmetric) encryption algorithm, parameterization, and an associated key.

func GenerateSKCipher

func GenerateSKCipher(algorithm string) (SKCipher, error)

GenerateSKCipher produces a SKCipher with a new random key following the given algorithm.

func NewSKCipher

func NewSKCipher(key PrivateKey) (SKCipher, error)

NewSKCipher creates a SKCipher wrapping the given secret key.

type SKCipherer

type SKCipherer interface {

	// Algorithm returns the label identifying the algorithm and
	// parameterization of this SKCipherer.
	Algorithm() string

	// Generate creates a new SKCipher.
	Generate() (SKCipher, error)

	// New wraps the given secret key as an SKCipher.
	New(key PrivateKey) (SKCipher, error)
}

An SKCipherer encapsulates key generation for a specific secret key (symmetric) encryption algorithm and parameterization.

type Signature

type Signature string

A Signature is a padded Base64-Standard encoded strings.

type Signer

type Signer interface {
	// PrivateKey returns a JSON Base64-URL encoded marshaling of the
	// credential's private key.
	PrivateKey() PrivateKey

	// Sign produces a signature for the given data.
	Sign(data []byte) (Signature, error)
}

Signer wraps a private key and can sign data.

type Subject

type Subject struct {
	ID        string
	PublicKey PublicKey
}

Subject associates a string identifier for some entity with its public key.

type Testament

type Testament struct {
	ID string // An optional identifier for this particular testament.

	Subject Subject // The subject of this assertion.
	Claims  Claims  // Arbitrary claims made about the subject, other than its identity.

	Expires string // Timepoint after which this Testament is to be considered invalid.
}

Testament captures an assertion about a given subject.

func NewTestament

func NewTestament(subjectID string, subjectkey PublicKey, claims Claims) *Testament

NewTestament generates a Testament for the subject and claims.

func UnpackTestament

func UnpackTestament(b64 string) (*Testament, error)

UnpackTestament parses a Testament from a JSON Base64-URL encoded string.

func (*Testament) Base64

func (x *Testament) Base64() (string, error)

Base64 encodes the Testament as a JSON Base64-URL encoded string.

func (*Testament) Sign

func (x *Testament) Sign(id string, signer Signer) (*Declaration, error)

Sign uses the given credentials to generate a Declaration, encapsulating the signer identity and a JSON Base64-URL encoding of the Testament.

type Verifier

type Verifier interface {
	// PublicKey returns a JSON Base64-URL encoded marshaling of the
	// credential's public key.
	PublicKey() PublicKey

	// Verify confirms that the given signature was produced from the
	// given data using the private key associated with this
	// credential's public key.  Any error indicates that it was not.
	Verify(data []byte, signature Signature) error
}

Verifier wraps a public key and can verify data.

type VerifierPool

type VerifierPool struct {
	// contains filtered or unexported fields
}

VerifierPool is a collection of verifiers. Typically these are used to group a set of keys for trusted entities that may be used to verify incoming data, etc..

func NewVerifierPool

func NewVerifierPool() *VerifierPool

NewVerifierPool creates an empty VerifierPool.

func (VerifierPool) Add

func (x VerifierPool) Add(id string, v Verifier) error

Add adds to given verifier to the pool under the given identifier.

func (VerifierPool) Verify

func (x VerifierPool) Verify(cert *Certificate) error

Verify confirms that each Declaration in the Certificate Chain was signed by the entitiy associated with the subsequent entry, that each intermediate signer was indicated by its successor to be a certificate authority, and that the chain at some point leads to an entry in the verifier pool.

func (VerifierPool) VerifyAny

func (x VerifierPool) VerifyAny(data []byte, signature Signature) error

VerifyAny checks if any entry in the pool can verify that the signature was created from the data by the private key associated with that verifier's public key.

func (VerifierPool) VerifyDeclaration

func (x VerifierPool) VerifyDeclaration(declaration *Declaration) error

VerifyDeclaration confirms that the declaration can be verified by the entry in the pool under the included signer identity if it is not blank, or by entry in the pool if it is.

func (VerifierPool) VerifySpecific

func (x VerifierPool) VerifySpecific(id string, data []byte, signature Signature) error

VerifySpecific looks up the given identifier in the pool and confirms that the signature was created from the data by the private key associated with that verifier's public key.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL