encrypt

package
v3.1.3 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2023 License: MIT Imports: 36 Imported by: 1

Documentation

Overview

Package encrypt contains some useful tools to deal with encryption/decryption

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AESEncryptFilesInDir

func AESEncryptFilesInDir(dir string, secret []byte, opts ...AESEncryptFilesInDirOption) (err error)

AESEncryptFilesInDir encrypt files in dir

will generate new encrypted files with <suffix> after ext

xxx.toml -> xxx.toml.enc

func AesDecrypt

func AesDecrypt(secret []byte, encrypted []byte) ([]byte, error)

AesDecrypt encrypt bytes by AES GCM

inspired by https://tutorialedge.net/golang/go-encrypt-decrypt-aes-tutorial/

The key argument should be 16, 24, or 32 bytes

func AesEncrypt

func AesEncrypt(secret []byte, cnt []byte) ([]byte, error)

AesEncrypt encrypt bytes by AES GCM

inspired by https://tutorialedge.net/golang/go-encrypt-decrypt-aes-tutorial/

The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func CSR2Der added in v3.1.0

func CSR2Der(csr *x509.CertificateRequest) []byte

CSR2Der marshal csr to der

func CSRDer2Pem added in v3.1.0

func CSRDer2Pem(CSRInDer []byte) (CSRInPem []byte)

CSRDer2Pem convert CSR in der to pem

func Cert2Der

func Cert2Der(cert *x509.Certificate) []byte

Cert2Der marshal private key by x509.8

func Cert2Pem

func Cert2Pem(cert *x509.Certificate) []byte

Cert2Pem marshal x509 certificate to pem

func CertDer2Pem

func CertDer2Pem(certInDer []byte) (certInPem []byte)

CertDer2Pem convert certificate in der to pem

func DecodeES256SignByBase64

func DecodeES256SignByBase64(sign string) (r, s *big.Int, err error)

DecodeES256SignByBase64 parse ecdsa signature string to two *big.Int

func DecodeES256SignByHex

func DecodeES256SignByHex(sign string) (r, s *big.Int, err error)

DecodeES256SignByHex parse ecdsa signature string to two *big.Int

func Der2CRL

func Der2CRL(crlDer []byte) (*x509.RevocationList, error)

Der2CRL parse crl der

func Der2CSR

func Der2CSR(csrDer []byte) (*x509.CertificateRequest, error)

Der2CSR parse crl der

func Der2Cert

func Der2Cert(certInDer []byte) (*x509.Certificate, error)

Der2Cert parse sigle certificate in der

func Der2Certs

func Der2Certs(certInDer []byte) ([]*x509.Certificate, error)

Der2Cert parse multiple certificates in der

func Der2Prikey

func Der2Prikey(prikeyDer []byte) (crypto.PrivateKey, error)

Der2Prikey parse private key from der in x509 v8/v1

func Der2Pubkey added in v3.1.0

func Der2Pubkey(pubkeyDer []byte) (crypto.PublicKey, error)

Der2Pubkey parse public key from der in x509 pkcs1/pkix

func DeriveKey added in v3.1.0

func DeriveKey(rawKey []byte, expectLen int) (newKey []byte, err error)

DeriveKey expand secret to specified length

func EncodeES256SignByBase64

func EncodeES256SignByBase64(r, s *big.Int) string

EncodeES256SignByBase64 format ecdsa signature to stirng

func EncodeES256SignByHex

func EncodeES256SignByHex(r, s *big.Int) string

EncodeES256SignByHex format ecdsa sign to stirng

func FormatBig2Base64

func FormatBig2Base64(b *big.Int) string

FormatBig2Base64 format big to base64 string

func FormatBig2Hex

func FormatBig2Hex(b *big.Int) string

FormatBig2Hex format big to hex string

func GeneratePasswordHash

func GeneratePasswordHash(password []byte) ([]byte, error)

GeneratePasswordHash generate hashed password by origin password

Example
// generate hashed password
rawPassword := []byte("1234567890")
hashedPassword, err := GeneratePasswordHash(rawPassword)
if err != nil {
	log.Shared.Error("try to generate password got error", zap.Error(err))
	return
}
fmt.Printf("got new hashed pasword: %v\n", string(hashedPassword))

// validate passowrd
if !ValidatePasswordHash(hashedPassword, rawPassword) {
	log.Shared.Error("password invalidate", zap.Error(err))
	return
}
Output:

func GetPubkeyFromPrikey

func GetPubkeyFromPrikey(priv crypto.PrivateKey) crypto.PublicKey

GetPubkeyFromPrikey get pubkey from private key

func HKDFWithSHA256

func HKDFWithSHA256(secret, salt, info []byte, results [][]byte) error

HKDFWithSHA256 derivative keys by HKDF with sha256. same key & salt will derivative same keys

Example

derivative multiple keys:

results := make([][]byte, 10)
for i := range results {
    results[i] = make([]byte, 20)
}
HKDFWithSHA256([]byte("your key"), nil, nil, results)

func HashSHA128String

func HashSHA128String(val string) string

HashSHA128String calculate string's hash by sha256

Example
val := testhashraw
got := HashSHA128String(val)
log.Shared.Info("hash", zap.String("got", got))
Output:

func HashSHA256String

func HashSHA256String(val string) string

HashSHA256String calculate string's hash by sha256

Example
val := testhashraw
got := HashSHA256String(val)
log.Shared.Info("hash", zap.String("got", got))
Output:

func HashXxhashString

func HashXxhashString(val string) string

HashXxhashString calculate string's hash by sha256

Example
val := testhashraw
got := HashXxhashString(val)
log.Shared.Info("hash", zap.String("got", got))
Output:

func NewECDSAPrikey

func NewECDSAPrikey(curve ECDSACurve) (*ecdsa.PrivateKey, error)

NewECDSAPrikey new ecdsa private key

func NewEd25519Prikey

func NewEd25519Prikey() (ed25519.PrivateKey, error)

NewEd25519Prikey new ed25519 private key

func NewRSAPrikey

func NewRSAPrikey(bits RSAPrikeyBits) (*rsa.PrivateKey, error)

NewRSAPrikey new rsa privat ekey

func NewRSAPrikeyAndCert

func NewRSAPrikeyAndCert(rsaBits RSAPrikeyBits, opts ...X509CertOption) (prikeyPem, certDer []byte, err error)

NewRSAPrikeyAndCert convient function to new rsa private key and cert

func NewX509CRL

func NewX509CRL(ca *x509.Certificate,
	prikey crypto.PrivateKey,
	revokeCerts []pkix.RevokedCertificate,
	opts ...X509CertOption) (crlDer []byte, err error)

NewX509CRL create and sign CRL

Args

  • ca: CA to sign CRL
  • prikey: prikey for CA
  • revokeCerts: certifacates that will be revoked

func NewX509CSR

func NewX509CSR(prikey crypto.PrivateKey, opts ...X509CertOption) (csrDer []byte, err error)

NewX509CSR new CSR

if prikey is not RSA private key, you must set SignatureAlgorithm by WithX509CertSignatureAlgorithm.

func NewX509Cert

func NewX509Cert(prikey crypto.PrivateKey, opts ...X509CertOption) (certDer []byte, err error)

NewX509Cert new self sign tls cert

func NewX509CertByCSR

func NewX509CertByCSR(
	ca *x509.Certificate,
	prikey crypto.PrivateKey,
	csrDer []byte,
	opts ...X509CertOption) (certDer []byte, err error)

NewX509CertByCSR sign CSR to certificate

csr's attributes will overweite option's attributes. you need verify csr manually before invoke this function.

func NewX509CertTemplate

func NewX509CertTemplate(opts ...X509CertOption) (tpl *x509.Certificate, err error)

NewX509CertTemplate new tls template

func ParseBase642Big

func ParseBase642Big(raw string) (*big.Int, error)

ParseBase642Big parse base64 string to big

func ParseHex2Big

func ParseHex2Big(hex string) (b *big.Int, ok bool)

ParseHex2Big parse hex string to big

func Pem2CSR added in v3.1.0

func Pem2CSR(csrInPem []byte) (*x509.CertificateRequest, error)

Pem2CSR parse csr from pem

func Pem2Cert

func Pem2Cert(certInPem []byte) (*x509.Certificate, error)

Pem2Cert parse single certificate in pem

func Pem2Certs

func Pem2Certs(certInPem []byte) ([]*x509.Certificate, error)

Pem2Certs parse multiple certificate in pem

func Pem2Der

func Pem2Der(pemBytes []byte) (derBytes []byte, err error)

Pem2Der convert pem to der

support one or more certs

func Pem2Ders added in v3.1.0

func Pem2Ders(pemBytes []byte) (dersBytes [][]byte, err error)

Pem2Ders convert pem to ders

support one or more certs

func Pem2Prikey

func Pem2Prikey(x509v8Pem []byte) (crypto.PrivateKey, error)

Pem2Prikey parse private key from x509 v8(general) pem

func Pem2Pubkey added in v3.1.0

func Pem2Pubkey(pubkeyPem []byte) (crypto.PublicKey, error)

Pem2Pubkey parse public key from pem

func Prikey2Der

func Prikey2Der(key crypto.PrivateKey) ([]byte, error)

Prikey2Der marshal private key by x509.8

func Prikey2Pem

func Prikey2Pem(key crypto.PrivateKey) ([]byte, error)

Prikey2Pem marshal private key to pem

func PrikeyDer2Pem

func PrikeyDer2Pem(prikeyInDer []byte) (prikeyInPem []byte)

PrikeyDer2Pem convert private key in der to pem

func Privkey2Signer

func Privkey2Signer(privkey crypto.PrivateKey) crypto.Signer

Privkey2Signer convert privkey to signer

func Pubkey2Der added in v3.1.0

func Pubkey2Der(key crypto.PublicKey) ([]byte, error)

Pubkey2Der marshal public key by pkix

func Pubkey2Pem added in v3.1.0

func Pubkey2Pem(key crypto.PublicKey) ([]byte, error)

Pubkey2Pem marshal public key to pem

func PubkeyDer2Pem added in v3.1.0

func PubkeyDer2Pem(pubkeyInDer []byte) (prikeyInPem []byte)

PubkeyDer2Pem convert public key in der to pem

func RSADecrypt added in v3.1.0

func RSADecrypt(prikey *rsa.PrivateKey, cipher []byte) (plain []byte, err error)

RSADecrypt decrypt by rsa PKCS1v15

only accept cipher encrypted by RSAEncrypt

func RSADer2Prikey

func RSADer2Prikey(x509v1Der []byte) (*rsa.PrivateKey, error)

RSADer2Prikey parse private key from x509 v1(rsa) der

func RSAEncrypt added in v3.1.0

func RSAEncrypt(pubkey *rsa.PublicKey, plain []byte) (cipher []byte, err error)

RSAEncrypt encrypt by PKCS1v15

canbe decrypt by RSADecrypt

func RSAPem2Prikey

func RSAPem2Prikey(x509v1Pem []byte) (*rsa.PrivateKey, error)

RSAPem2Prikey parse private key from x509 v1(rsa) pem

func Salt

func Salt(length int) ([]byte, error)

Salt generate random salt with specifiec length

func SecureCipherSuites

func SecureCipherSuites(filter func(*tls.CipherSuite) bool) []uint16

SecureCipherSuites get golang built-in cipher suites without known insecure suites

func SignByECDSAWithSHA256

func SignByECDSAWithSHA256(priKey *ecdsa.PrivateKey, content []byte) (r, s *big.Int, err error)

SignByECDSAWithSHA256 generate signature by ecdsa private key use sha256

Example
priKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
	log.Shared.Panic("generate key", zap.Error(err))
}
priKey2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
	log.Shared.Panic("generate key", zap.Error(err))
}

// case: correct key
cnt := []byte("fjijf23lijfl23ijrl32jra9pfie9wpfi")
r, s, err := SignByECDSAWithSHA256(priKey, cnt)
if err != nil {
	log.Shared.Panic("sign", zap.Error(err))
}
if !VerifyByECDSAWithSHA256(&priKey.PublicKey, cnt, r, s) {
	log.Shared.Panic("verify failed")
}

// generate string
encoded := EncodeES256SignByBase64(r, s)
if _, _, err = DecodeES256SignByBase64(encoded); err != nil {
	log.Shared.Panic("encode and decode", zap.Error(err))
}

// case: incorrect cnt
cnt = []byte("fjijf23lijfl23ijrl32jra9pfie9wpfi")
r, s, err = SignByECDSAWithSHA256(priKey, cnt)
if err != nil {
	log.Shared.Panic("sign", zap.Error(err))
}
if VerifyByECDSAWithSHA256(&priKey.PublicKey, append(cnt, '2'), r, s) {
	log.Shared.Panic("should not verify")
}

// case: incorrect key
r, s, err = SignByECDSAWithSHA256(priKey2, cnt)
if err != nil {
	log.Shared.Panic("sign", zap.Error(err))
}
if VerifyByECDSAWithSHA256(&priKey.PublicKey, cnt, r, s) {
	log.Shared.Panic("should not verify")
}
Output:

func SignByECDSAWithSHA256AndBase64

func SignByECDSAWithSHA256AndBase64(priKey *ecdsa.PrivateKey, content []byte) (signature string, err error)

SignByECDSAWithSHA256AndBase64 generate signature by ecdsa private key use sha256

func SignByRSAWithSHA256

func SignByRSAWithSHA256(priKey *rsa.PrivateKey, content []byte) ([]byte, error)

SignByRSAWithSHA256 generate signature by rsa private key use sha256

func SignReaderByECDSAWithSHA256

func SignReaderByECDSAWithSHA256(priKey *ecdsa.PrivateKey, reader io.Reader) (r, s *big.Int, err error)

SignReaderByECDSAWithSHA256 generate signature by ecdsa private key use sha256

func SignReaderByRSAWithSHA256

func SignReaderByRSAWithSHA256(priKey *rsa.PrivateKey, reader io.Reader) (sig []byte, err error)

SignReaderByRSAWithSHA256 generate signature by rsa private key use sha256

func ValidatePasswordHash

func ValidatePasswordHash(hashedPassword, password []byte) bool

ValidatePasswordHash validate password is match with hashedPassword

func VerifyByECDSAWithSHA256

func VerifyByECDSAWithSHA256(pubKey *ecdsa.PublicKey, content []byte, r, s *big.Int) bool

VerifyByECDSAWithSHA256 verify signature by ecdsa public key use sha256

func VerifyByECDSAWithSHA256AndBase64

func VerifyByECDSAWithSHA256AndBase64(pubKey *ecdsa.PublicKey, content []byte, signature string) (bool, error)

VerifyByECDSAWithSHA256 verify signature by ecdsa public key use sha256

func VerifyByRSAWithSHA256

func VerifyByRSAWithSHA256(pubKey *rsa.PublicKey, content []byte, sig []byte) error

VerifyByRSAWithSHA256 verify signature by rsa public key use sha256

func VerifyCRL

func VerifyCRL(ca *x509.Certificate, crl *x509.RevocationList) error

VerifyCRL verify crl by ca

func VerifyCertByPrikey added in v3.1.0

func VerifyCertByPrikey(certPem []byte, prikeyPem []byte) error

VerifyCertByPrikey verify cert by prikey

func VerifyReaderByECDSAWithSHA256

func VerifyReaderByECDSAWithSHA256(pubKey *ecdsa.PublicKey, reader io.Reader, r, s *big.Int) (bool, error)

VerifyReaderByECDSAWithSHA256 verify signature by ecdsa public key use sha256

func VerifyReaderByRSAWithSHA256

func VerifyReaderByRSAWithSHA256(pubKey *rsa.PublicKey, reader io.Reader, sig []byte) error

VerifyReaderByRSAWithSHA256 verify signature by rsa public key use sha256

Types

type AESEncryptFilesInDirOption

type AESEncryptFilesInDirOption func(*encryptFilesOption) error

AESEncryptFilesInDirOption options to encrypt files in dir

func WithAESFilesInDirFileExt

func WithAESFilesInDirFileExt(ext string) AESEncryptFilesInDirOption

WithAESFilesInDirFileExt only encrypt files with specific ext

func WithAESFilesInDirFileSuffix

func WithAESFilesInDirFileSuffix(suffix string) AESEncryptFilesInDirOption

WithAESFilesInDirFileSuffix will append to encrypted's filename as suffix

xxx.toml -> xxx.toml.enc

type AesReaderWrapper

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

AesReaderWrapper used to decrypt encrypted reader

func NewAesReaderWrapper

func NewAesReaderWrapper(in io.Reader, key []byte) (*AesReaderWrapper, error)

NewAesReaderWrapper wrap reader by aes

func (*AesReaderWrapper) Read

func (w *AesReaderWrapper) Read(p []byte) (n int, err error)

type DHKX

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

Diffie Hellman Key-exchange algorithm

https://pkg.go.dev/github.com/monnand/dhkx

Example

alice, _ := NewDHKX()
bob, _ := NewDHKX()

alicePub := alice.PublicKey()
bobPub := bob.PublicKey()

aliceKey, _ := alice.GenerateKey(bobPub)
bobKey, _ := bob.GenerateKey(alicePub)

// aliceKey == bobKey
Example
alice, _ := NewDHKX()

bob, _ := NewDHKX()

alicePub := alice.PublicKey()
bobPub := bob.PublicKey()

aliceKey, _ := alice.GenerateKey(bobPub)
bobKey, _ := bob.GenerateKey(alicePub)
fmt.Println(reflect.DeepEqual(aliceKey, bobKey))
Output:

true

func NewDHKX

func NewDHKX(optfs ...DHKXOptionFunc) (d *DHKX, err error)

NewDHKX create a new DHKX instance

each DHKX instance has it's unique group and private key

func (*DHKX) GenerateKey

func (d *DHKX) GenerateKey(peerPubKey []byte) ([]byte, error)

GenerateKey generate new key by peer's public key

each side of the DHKX exchange peers will generate the same key

key like:

60a425ca3a4cc313db9c113a0526f3809725305afc68e1accd0e653ae8d0182c6eb05557f4b5d094
f015972b9fda7d60c1b64d79f50baea7365d858ede0fb7a6571403d4b95f682144b56fa17ffcbe9e
70de69dc0045672696e683c423c5b3dfc02a6916be1e50c74e60353ec08a465cc124e8ca88337fb7
4a0370e17a7cedb0b1e76733f43ad3db9e3d29ab43c75686a8bc4a88ee46addbd1590c8277d1b1ef
42aded6cc0bfe0a7ff8933861dae772c755087f2a41021f4ca53867ba49797d111ef21b381cb6441
178f4ccd3748f8e7b1a12ec3799571a49fc0aa793c05ab6e228b559f1fda2912542d7246388ccec1
38b4d8ce9df4a32c198891c4e33b5034

func (*DHKX) PublicKey

func (d *DHKX) PublicKey() []byte

PublicKey return public key bytes

type DHKXOptionFunc

type DHKXOptionFunc func(*dhkxOption) error

DHKXOptionFunc optional func to set dhkx option

type ECDSACurve

type ECDSACurve string

ECDSACurve algorithms

const (
	// ECDSACurveP224 ecdsa with P224
	ECDSACurveP224 ECDSACurve = "P224"
	// ECDSACurveP256 ecdsa with P256
	ECDSACurveP256 ECDSACurve = "P256"
	// ECDSACurveP384 ecdsa with P384
	ECDSACurveP384 ECDSACurve = "P384"
	// ECDSACurveP521 ecdsa with P521
	ECDSACurveP521 ECDSACurve = "P521"
)

type RSAPrikeyBits

type RSAPrikeyBits int

RSAPrikeyBits width of rsa private key

const (
	// RSAPrikeyBits2048 rsa private key with 2048 bits
	RSAPrikeyBits2048 RSAPrikeyBits = 2048
	// RSAPrikeyBits3072 rsa private key with 3072 bits
	RSAPrikeyBits3072 RSAPrikeyBits = 3072
)

type X509CertOption

type X509CertOption func(*tlsCertOption) error

X509CertOption option to generate tls certificate

func WithX509CertCommonName

func WithX509CertCommonName(commonName string) X509CertOption

WithX509CertCommonName set common name

func WithX509CertIsCA

func WithX509CertIsCA() X509CertOption

WithX509CertIsCA set is ca

func WithX509CertIsCRLCA added in v3.1.2

func WithX509CertIsCRLCA() X509CertOption

WithX509CertIsCRLCA set is ca to sign CRL

func WithX509CertKeyUsage added in v3.1.2

func WithX509CertKeyUsage(usage x509.KeyUsage) X509CertOption

WithX509CertKeyUsage add key usage

func WithX509CertLocality added in v3.1.0

func WithX509CertLocality(l ...string) X509CertOption

WithX509CertLocality set organization unit

func WithX509CertOrganization

func WithX509CertOrganization(organization ...string) X509CertOption

WithX509CertOrganization set organization

func WithX509CertOrganizationUnit added in v3.1.0

func WithX509CertOrganizationUnit(ou ...string) X509CertOption

WithX509CertOrganizationUnit set organization unit

func WithX509CertSANS added in v3.1.2

func WithX509CertSANS(sans ...string) X509CertOption

WithX509CertSANS set certificate SANs

auto parse to ip/email/url/dns

func WithX509CertSignatureAlgorithm

func WithX509CertSignatureAlgorithm(sigAlg x509.SignatureAlgorithm) X509CertOption

WithX509CertSignatureAlgorithm set signature algorithm

func WithX509CertValidFor

func WithX509CertValidFor(validFor time.Duration) X509CertOption

WithX509CertValidFor set valid for duration

func WithX509CertValidFrom

func WithX509CertValidFrom(validFrom time.Time) X509CertOption

WithX509CertValidFrom set valid from

func WithX509ExtCertKeyUsage added in v3.1.2

func WithX509ExtCertKeyUsage(usage ...x509.ExtKeyUsage) X509CertOption

WithX509ExtCertKeyUsage add key usage

Jump to

Keyboard shortcuts

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