openssl

package module
v4.2.2 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2023 License: Apache-2.0 Imports: 15 Imported by: 14

README

Go Report Card

Luzifer / go-openssl

go-openssl is a small library wrapping the crypto/aes functions in a way the output is compatible to OpenSSL / CryptoJS. For all encryption / decryption processes AES256 is used so this library will not be able to decrypt messages generated with other than openssl aes-256-cbc. If you're using CryptoJS to process the data you also need to use AES256 on that side.

Version support

For this library only the latest major version is supported. All prior major versions should no longer be used.

The versioning is following SemVer which means upgrading to a newer major version will break your code!

OpenSSL compatibility

1.1.0c

Starting with v2.0.0 go-openssl generates the encryption keys using sha256sum algorithm. This is the default introduced in OpenSSL 1.1.0c. When encrypting data you can choose which digest method to use and therefore also continue to use md5sum. When decrypting OpenSSL encrypted data md5sum, sha1sum and sha256sum are supported.

1.1.1

Starting with v4.0.0 go-openssl is capable of using the PBKDF2 key derivation method for encryption. You can choose to use it by passing the corresponding CredsGenerator.

Installation

# Get the latest version
go get github.com/Luzifer/go-openssl/v4

Usage example

The usage is quite simple as you don't need any special knowledge about OpenSSL and/or AES256:

Encrypt
import (
  "fmt"
  openssl "github.com/Luzifer/go-openssl/v4"
)

func main() {
  plaintext := "Hello World!"
  passphrase := "z4yH36a6zerhfE5427ZV"

  o := openssl.New()

  enc, err := o.EncryptBytes(passphrase, []byte(plaintext), PBKDF2SHA256)
  if err != nil {
    fmt.Printf("An error occurred: %s\n", err)
  }

  fmt.Printf("Encrypted text: %s\n", string(enc))
}
Decrypt
import (
  "fmt"
  openssl "github.com/Luzifer/go-openssl/v4"
)

func main() {
  opensslEncrypted := "U2FsdGVkX19ZM5qQJGe/d5A/4pccgH+arBGTp+QnWPU="
  passphrase := "z4yH36a6zerhfE5427ZV"

  o := openssl.New()

  dec, err := o.DecryptBytes(passphrase, []byte(opensslEncrypted), BytesToKeyMD5)
  if err != nil {
    fmt.Printf("An error occurred: %s\n", err)
  }

  fmt.Printf("Decrypted text: %s\n", string(dec))
}

Testing

To execute the tests for this library you need to be on a system having /bin/bash and openssl available as the compatibility of the output is tested directly against the openssl binary. The library itself should be usable on all operating systems supported by Go and crypto/aes.

Documentation

Overview

Package openssl contains a pure Go implementation of an OpenSSL compatible encryption / decryption

Index

Examples

Constants

View Source
const DefaultPBKDF2Iterations = 10000

DefaultPBKDF2Iterations specifies the number of iterations to use in PBKDF2 key generation. This is taken from the `openssl enc` commands default.

Taken from OpenSSL v3.1.2: `openssl enc --help |& grep -A1 iter`

Variables

View Source
var (
	// BytesToKeyMD5 utilizes MD5 key-derivation (`-md md5`)
	BytesToKeyMD5 = NewBytesToKeyGenerator(md5.New)
	// BytesToKeySHA1 utilizes SHA1 key-derivation (`-md sha1`)
	BytesToKeySHA1 = NewBytesToKeyGenerator(sha1.New)
	// BytesToKeySHA256 utilizes SHA256 key-derivation (`-md sha256`)
	BytesToKeySHA256 = NewBytesToKeyGenerator(sha256.New)
	// BytesToKeySHA384 utilizes SHA384 key-derivation (`-md sha384`)
	BytesToKeySHA384 = NewBytesToKeyGenerator(sha512.New384)
	// BytesToKeySHA512 utilizes SHA512 key-derivation (`-md sha512`)
	BytesToKeySHA512 = NewBytesToKeyGenerator(sha512.New)
	// PBKDF2MD5 utilizes PBKDF2 key derivation with MD5 hashing (`-pbkdf2 -md md5`)
	PBKDF2MD5 = NewPBKDF2Generator(md5.New, DefaultPBKDF2Iterations)
	// PBKDF2SHA1 utilizes PBKDF2 key derivation with SHA1 hashing (`-pbkdf2 -md sha1`)
	PBKDF2SHA1 = NewPBKDF2Generator(sha1.New, DefaultPBKDF2Iterations)
	// PBKDF2SHA256 utilizes PBKDF2 key derivation with SHA256 hashing (`-pbkdf2 -md sha256`)
	PBKDF2SHA256 = NewPBKDF2Generator(sha256.New, DefaultPBKDF2Iterations)
	// PBKDF2SHA384 utilizes PBKDF2 key derivation with SHA384 hashing (`-pbkdf2 -md sha384`)
	PBKDF2SHA384 = NewPBKDF2Generator(sha512.New384, DefaultPBKDF2Iterations)
	// PBKDF2SHA512 utilizes PBKDF2 key derivation with SHA512 hashing (`-pbkdf2 -md sha512`)
	PBKDF2SHA512 = NewPBKDF2Generator(sha512.New, DefaultPBKDF2Iterations)
)
View Source
var ErrInvalidSalt = errors.New("salt needs to have exactly 8 byte")

ErrInvalidSalt is returned when a salt with a length of != 8 byte is passed

Functions

This section is empty.

Types

type Creds

type Creds struct {
	Key []byte
	IV  []byte
}

Creds holds a key and an IV for encryption methods

type CredsGenerator

type CredsGenerator func(password, salt []byte) (Creds, error)

CredsGenerator are functions to derive a key and iv from a password and a salt

func NewBytesToKeyGenerator

func NewBytesToKeyGenerator(hashFunc func() hash.Hash) CredsGenerator

NewBytesToKeyGenerator implements the openSSLEvpBytesToKey key derivation functions described in the OpenSSL code as follows:

openSSLEvpBytesToKey follows the OpenSSL (undocumented?) convention for extracting the key and IV from passphrase. It uses the EVP_BytesToKey() method which is basically: D_i = HASH^count(D_(i-1) || password || salt) where || denotes concatentaion, until there are sufficient bytes available 48 bytes since we're expecting to handle AES-256, 32bytes for a key and 16bytes for the IV

func NewPBKDF2Generator

func NewPBKDF2Generator(hashFunc func() hash.Hash, iterations int) CredsGenerator

NewPBKDF2Generator implements a credential generator compatible with the OpenSSL `-pbkdf2` parameter

type DecryptReader added in v4.2.0

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

DecryptReader represents an io.Reader for OpenSSL encrypted data

func NewReader added in v4.2.0

func NewReader(r io.Reader, passphrase string, cg CredsGenerator) *DecryptReader

NewReader creates a new OpenSSL stream reader with underlying reader, passphrase and CredsGenerator

func (*DecryptReader) Read added in v4.2.0

func (d *DecryptReader) Read(b []byte) (int, error)

Read implements the io.Reader interface to read from an encrypted datastream

type EncryptWriter added in v4.2.0

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

EncryptWriter represents an io.WriteCloser info OpenSSL encrypted data

func NewWriter added in v4.2.0

func NewWriter(w io.Writer, passphrase string, cg CredsGenerator) *EncryptWriter

NewWriter create new openssl stream writer with underlying writer, passphrase and CredsGenerator.

Make sure close the writer after writing all data, to ensure the remaining data is padded and written to the underlying writer.

func (*EncryptWriter) Close added in v4.2.0

func (e *EncryptWriter) Close() error

Close writes any buffered data to the underlying io.Writer. Make sure close the writer after write all data.

func (*EncryptWriter) Write added in v4.2.0

func (e *EncryptWriter) Write(b []byte) (int, error)

Write implements io.WriteCloser to write encrypted data into the underlying writer. The Write call may keep data in the buffer and needs to flush them through the Close function.

type OpenSSL

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

OpenSSL is a helper to generate OpenSSL compatible encryption with autmatic IV derivation and storage. As long as the key is known all data can also get decrypted using OpenSSL CLI. Code from http://dequeue.blogspot.de/2014/11/decrypting-something-encrypted-with.html

func New

func New() *OpenSSL

New instanciates and initializes a new OpenSSL encrypter

func (OpenSSL) DecryptBinaryBytes

func (o OpenSSL) DecryptBinaryBytes(passphrase string, encryptedData []byte, cg CredsGenerator) ([]byte, error)

DecryptBinaryBytes takes a slice of binary bytes, encrypted data to decrypt and a key-derivation function. The key-derivation function must match the function used to encrypt the data. (In OpenSSL the value of the `-md` parameter.)

You should not just try to loop the digest functions as this will cause a race condition and you will not be able to decrypt your data properly.

func (OpenSSL) DecryptBytes

func (o OpenSSL) DecryptBytes(passphrase string, encryptedBase64Data []byte, cg CredsGenerator) ([]byte, error)

DecryptBytes takes a slice of bytes with base64 encoded, encrypted data to decrypt and a key-derivation function. The key-derivation function must match the function used to encrypt the data. (In OpenSSL the value of the `-md` parameter.)

You should not just try to loop the digest functions as this will cause a race condition and you will not be able to decrypt your data properly.

Example

#nosec G101 -- Contains harcoded test passphrase

opensslEncrypted := "U2FsdGVkX19ZM5qQJGe/d5A/4pccgH+arBGTp+QnWPU="
passphrase := "z4yH36a6zerhfE5427ZV"

o := New()

dec, err := o.DecryptBytes(passphrase, []byte(opensslEncrypted), BytesToKeyMD5)
if err != nil {
	fmt.Printf("An error occurred: %s\n", err)
}

fmt.Printf("Decrypted text: %s\n", string(dec))
Output:

Decrypted text: hallowelt

func (OpenSSL) EncryptBinaryBytes

func (o OpenSSL) EncryptBinaryBytes(passphrase string, plainData []byte, cg CredsGenerator) ([]byte, error)

EncryptBinaryBytes encrypts a slice of bytes in a manner compatible to OpenSSL encryption functions using AES-256-CBC as encryption algorithm. This function generates a random salt on every execution.

func (OpenSSL) EncryptBinaryBytesWithSaltAndDigestFunc

func (o OpenSSL) EncryptBinaryBytesWithSaltAndDigestFunc(passphrase string, salt, plainData []byte, cg CredsGenerator) ([]byte, error)

EncryptBinaryBytesWithSaltAndDigestFunc encrypts a slice of bytes in a manner compatible to OpenSSL encryption functions using AES-256-CBC as encryption algorithm. The salt needs to be passed in here which ensures the same result on every execution on cost of a much weaker encryption as with EncryptString.

The salt passed into this function needs to have exactly 8 byte.

The hash function corresponds to the `-md` parameter of OpenSSL. For OpenSSL pre-1.1.0c DigestMD5Sum was the default, since then it is DigestSHA256Sum.

If you don't have a good reason to use this, please don't! For more information see this: https://en.wikipedia.org/wiki/Salt_(cryptography)#Common_mistakes

func (OpenSSL) EncryptBytes

func (o OpenSSL) EncryptBytes(passphrase string, plainData []byte, cg CredsGenerator) ([]byte, error)

EncryptBytes encrypts a slice of bytes that are base64 encoded in a manner compatible to OpenSSL encryption functions using AES-256-CBC as encryption algorithm. This function generates a random salt on every execution.

Example

#nosec G101 -- Contains harcoded test passphrase

plaintext := "Hello World!"
passphrase := "z4yH36a6zerhfE5427ZV"

o := New()

enc, err := o.EncryptBytes(passphrase, []byte(plaintext), PBKDF2SHA256)
if err != nil {
	fmt.Printf("An error occurred: %s\n", err)
}

fmt.Printf("Encrypted text: %s\n", string(enc))
Output:

func (OpenSSL) EncryptBytesWithSaltAndDigestFunc

func (o OpenSSL) EncryptBytesWithSaltAndDigestFunc(passphrase string, salt, plainData []byte, cg CredsGenerator) ([]byte, error)

EncryptBytesWithSaltAndDigestFunc encrypts a slice of bytes that are base64 encoded in a manner compatible to OpenSSL encryption functions using AES-256-CBC as encryption algorithm. The salt needs to be passed in here which ensures the same result on every execution on cost of a much weaker encryption as with EncryptString.

The salt passed into this function needs to have exactly 8 byte.

The hash function corresponds to the `-md` parameter of OpenSSL. For OpenSSL pre-1.1.0c DigestMD5Sum was the default, since then it is DigestSHA256Sum.

If you don't have a good reason to use this, please don't! For more information see this: https://en.wikipedia.org/wiki/Salt_(cryptography)#Common_mistakes

func (OpenSSL) GenerateSalt

func (OpenSSL) GenerateSalt() ([]byte, error)

GenerateSalt generates a random 8 byte salt

func (OpenSSL) MustGenerateSalt

func (o OpenSSL) MustGenerateSalt() []byte

MustGenerateSalt is a wrapper around GenerateSalt which will panic on an error. This allows you to use this function as a parameter to EncryptBytesWithSaltAndDigestFunc

Jump to

Keyboard shortcuts

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