cryptoengine

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2024 License: ISC Imports: 20 Imported by: 1

README

cryptoengine

This simplifies even further the usage of the NaCl crypto primitives, by taking care of the nonce part. It uses a KDF, specifically HKDF to compute the nonces.

Current Status

Build Linter CodeQL Go Report Card Go Reference

Big Picture

The encryption and decryption phases are the following:

Message -> Encrypt -> EncryptedMessage -> ToBytes() -> < = NETWORK = >  <- FromBytes() -> EncryptedMessage -> Decrypt -> Message

Usage

    1. Import the library
    import github.com/pilinux/cryptoengine
    
    1. Instantiate the CryptoEngine object via:
    engine, err := cryptoengine.InitCryptoEngine("Sec51")
    if err != nil {
      return err
    }
    

See the go doc for more info about the InitCryptoEngine parameter

    1. Encrypt a message using symmetric encryption
    message := "the quick brown fox jumps over the lazy dog"
    engine.NewMessage(message)
    if err != nil {
      return err
    }
    
    1. Serialize the message to a byte slice, so that it can be safely sent to the network
    messageBytes, err := tcp.ToBytes()
    if err != nil {
      t.Fatal(err)
    }
    
    1. Parse the byte slice back to a message
  message, err := MessageFromBytes(messageBytes)
  if err != nil {
    t.Fatal(err)
  }

License

Copyright (c) 2015 Sec51.com info@sec51.com

Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Documentation

Overview

Package cryptoengine simplifies the usage of the NaCl crypto primitives, by taking care of the nonce part. It uses a KDF, specifically HKDF to compute the nonces.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorKeySize           = fmt.Errorf("the provisioned key size is less than: %d", keySize)
	ErrorKeyNotValid       = fmt.Errorf("the provisioned public key is not valid")
	ErrorSaltGeneration    = fmt.Errorf("could not generate random salt")
	ErrorKeyGeneration     = fmt.Errorf("could not generate random key")
	ErrorMessageDecryption = fmt.Errorf("could not verify the message - message has been tempered with")
	ErrorMessageParsing    = fmt.Errorf("could not parse the Message from bytes")
	ErrorMessageEmpty      = fmt.Errorf("cannot encrypt an empty message")
)

errors

Functions

This section is empty.

Types

type CryptoEngine

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

CryptoEngine is the basic object which needs to be instantiated for encrypting messages either via public key cryptography or private key cryptography

The object has the methods necessary to execute all the needed functions to encrypt and decrypt a message, both with symmetric and asymmetric crypto

func InitCryptoEngine

func InitCryptoEngine(communicationIdentifier string) (*CryptoEngine, error)

InitCryptoEngine function initializes all the necessary information to carry out a secure communication either via public key cryptography or secret key cryptography. The peculiarity is that the user of this package needs to take care of only one parameter, the communicationIdentifier. It defines a unique set of keys between the application and the communicationIdentifier unique end point.

IMPORTANT: The parameter communicationIdentifier defines several assumptions the code use:

  • it names the secret key files with the communicationIdentifier prefix. This means that if you want to have different secret keys with different end points, you can differentiate the key by having different unique communicationIdentifier. It, also, loads the already created keys back in memory based on the communicationIdentifier

  • it does the same with the asymmetric keys

The communicationIdentifier parameter is URL unescape, trimmed, set to lower case and all the white spaces are replaced with an underscore. The publicKey parameter can be nil. In that case the CryptoEngine assumes it has been instantiated for symmetric crypto usage.

func (*CryptoEngine) Decrypt

func (engine *CryptoEngine) Decrypt(encryptedBytes []byte) (*Message, error)

Decrypt is used to decrypt messages where symmetric encryption is used.

func (*CryptoEngine) DecryptWithPublicKey

func (engine *CryptoEngine) DecryptWithPublicKey(encryptedBytes []byte, verificationEngine VerificationEngine) (*Message, error)

DecryptWithPublicKey is used to decrypt messages where symmetric encryption is used.

func (*CryptoEngine) NewEncryptedMessage

func (engine *CryptoEngine) NewEncryptedMessage(msg Message) (EncryptedMessage, error)

NewEncryptedMessage accepts a message , then encrypts its Version+Type+Text using a symmetric key.

func (*CryptoEngine) NewEncryptedMessageWithPubKey

func (engine *CryptoEngine) NewEncryptedMessageWithPubKey(msg Message, verificationEngine VerificationEngine) (EncryptedMessage, error)

NewEncryptedMessageWithPubKey accepts the message as byte slice and the public key of the receiver of the message, then encrypts it using the asymmetric key public key. If the public key is not provisioned and does not have the required length of 32 bytes it raises an exception.

func (*CryptoEngine) PublicKey

func (engine *CryptoEngine) PublicKey() []byte

PublicKey gives access to the public key.

type EncryptedMessage

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

EncryptedMessage struct represent the encrypted message which can be sent over the network safely.

|length| => 8 bytes (uint64 total message length)

|nonce| => 24 bytes ([]byte size)

|message| => N bytes ([]byte message)

func (EncryptedMessage) ToBytes

func (m EncryptedMessage) ToBytes() ([]byte, error)

ToBytes converts the encrypted message to bytes

STRUCTURE

8 => |SIZE|

24 => |NONCE|

N => |DATA|

|size| => 8 bytes (uint64 total message length)

|type| => 4 bytes (int message version)

|message| => N bytes ([]byte message)

type Message added in v0.1.1

type Message struct {
	Version int    // version of the message, done to support backward compatibility
	Type    int    // message type - this can be used on the receiver part to process different types
	Text    string // the encrypted message
}

Message struct encapsulates the encrypted message in a TCP packet, in an easily parsable format. We assume the data is always encrypted.

Format:

|version| => 8 bytes (uint64 total message length)

|type| => 4 bytes (int message version)

|message| => N bytes ([]byte message)

func NewMessage

func NewMessage(clearText string, messageType int) (Message, error)

NewMessage creates a new message with a clear text and the message type.

messageType: is an identifier to distinguish the messages on the receiver and parse them

for example if zero is a JSON message and 1 is XML, then the received can parse different formats with different methods

type VerificationEngine

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

VerificationEngine links two peers basically. It holds the public key and the remote peer public key and the pre-shared key.

func NewVerificationEngine

func NewVerificationEngine(context string) (VerificationEngine, error)

NewVerificationEngine instantiates the verification engine by leveraging the context. Basically if a public key of a peer is available locally, then it's loaded here.

func NewVerificationEngineWithKey

func NewVerificationEngineWithKey(publicKey []byte) (VerificationEngine, error)

NewVerificationEngineWithKey instantiates the verification engine by passing it the key (at the moment only the public key). go nacl crypto does not support Ed25519 signatures yet.

func (VerificationEngine) PublicKey

func (e VerificationEngine) PublicKey() [keySize]byte

PublicKey returns the public key of the peer.

Directories

Path Synopsis
fuzzing
messagefrombytes
this file is used for fuzz testing only
this file is used for fuzz testing only

Jump to

Keyboard shortcuts

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