cry

package
v0.0.0-...-9d95335 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2024 License: MIT Imports: 17 Imported by: 0

README

gocrypt

gocrypt is encryption/decryption library for golang.

Library gocrypt provides a library to do encryption instruct with go field. The library gocrypt provide instruct tag encryption or inline encryption and decryption

The package supported:

DES3 — Triple Data Encryption Standard

The DES ciphers are primarily supported for PBE standard that provides the option of generating an encryption key based on a passphrase.

AES — Advanced Encryption Standard

The AES cipher is the current U.S. government standard for all software and is recognized worldwide.

RC4 — stream chipper

The RC4 is supplied for situations that call for fast encryption, but not strong encryption. RC4 is ideal for situations that require a minimum of encryption.

The Idea

Sample JSON Payload

Before the encryption:

{
    "a": "Sample plain text",
    "b": {
        c: "Sample plain text 2"
    }
}

After the encryption:

{
    "profile": "akldfjiaidjfods==",
    "id": {
        c: "Ijdsifsjiek18239=="
    }
}
Struct Tag Field Implementation
type A struct {
    A string    `json:"a" gocrypt:"aes"`
    B B         `json:"b"`
}

type B struct {
    C string    `json:"c" gocrypt:"aes"`
}

Full Sample

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/firdasafridi/gocrypt"
)

// Data contains identity and profile user
type Data struct {
	Profile  *Profile  `json:"profile"`
	Identity *Identity `json:"identity"`
}

// Profile contains name and phone number user
type Profile struct {
	Name        string `json:"name"`
	PhoneNumber string `json:"phone_number" gocrypt:"aes"`
}

// Identity contains id, license number, and expired date
type Identity struct {
	ID            string    `json:"id" gocrypt:"aes"`
	LicenseNumber string    `json:"license_number" gocrypt:"aes"`
	ExpiredDate   time.Time `json:"expired_date"`
}

const (
	// it's random string must be hexa  a-f & 0-9
	aeskey = "fa89277fb1e1c344709190deeac4465c2b28396423c8534a90c86322d0ec9dcf"
)

func main() {

	// define AES option
	aesOpt, err := gocrypt.NewAESOpt(aeskey)
	if err != nil {
		log.Println("ERR", err)
		return
	}

	data := &Data{
		Profile: &Profile{
			Name:        "Batman",
			PhoneNumber: "+62123123123",
		},
		Identity: &Identity{
			ID:            "12345678",
			LicenseNumber: "JSKI-123-456",
		},
	}

	cryptRunner := gocrypt.New(&gocrypt.Option{
		AESOpt: aesOpt,
	})

	err = cryptRunner.Encrypt(data)
	if err != nil {
		log.Println("ERR", err)
		return
	}
	strEncrypt, _ := json.Marshal(data)
	fmt.Println("Encrypted:", string(strEncrypt))

	err = cryptRunner.Decrypt(data)
	if err != nil {
		log.Println("ERR", err)
		return
	}
	strDecrypted, _ := json.Marshal(data)
	fmt.Println("Decrypted:", string(strDecrypted))
}

Others

gocrypt also supported inline encryption/decryption.

	func main() {
        // sample plain text
        sampleText := "Halo this is encrypted text!!!"

        // define DES option
        desOpt, err := gocrypt.NewDESOpt(key)
        if err != nil {
            log.Println("ERR", err)
            return
        }

        // Encrypt text using DES algorithm
        cipherText, err := desOpt.Encrypt([]byte(sampleText))
        if err != nil {
            log.Println("ERR", err)
            return
        }
        fmt.Println("Encrypted data:", cipherText)

        // Decrypt text using DES algorithm
        plainText, err := desOpt.Decrypt([]byte(cipherText))
        if err != nil {
            log.Println("ERR", err)
            return
        }
        fmt.Println("Decrypted data:", plainText)
    }

Limitation

gocrypt only supports the string type. Need more research & development to support the library for more type data.

Documentation

Overview

Package gocrypt provide a library for do encryption in struct with go field.

Package gocrypt provide in struct tag encryption or inline encryption and decryption

The package supported:

DES3 — Triple Data Encryption Standard

AES/GCM — Advanced Encryption Standard

RC4 — stream chipper

The AES cipher is the current U.S. government standard for all software, and is recognized worldwide.

The DES ciphers are primarily supported for PBE standard that provides the option of generating an encryption key based on a passphrase.

The RC4 is supplied for situations that call for fast encryption, but not strong encryption. RC4 is ideal for situations that require a minimum of encryption.

Index

Examples

Constants

View Source
const (
	// GOCRYPT is variable tag field for gocrypt
	GOCRYPT = "gocrypt"
)

Variables

This section is empty.

Functions

func DecryptWithPrivateKey

func DecryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error)

DecryptWithPrivateKey decrypts data with private key.

func EncryptWithPublicKey

func EncryptWithPublicKey(msg []byte, pub *rsa.PublicKey) ([]byte, error)

EncryptWithPublicKey encrypts data with public key.

func ExportPrivateKey

func ExportPrivateKey(key *rsa.PrivateKey) []byte

ExportPrivateKey exports private key to bytes.

func ExportPublicKey

func ExportPublicKey(pub *rsa.PublicKey) []byte

ExportPublicKey exports public key to bytes.

func GenerateKeyPair

func GenerateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey)

GenerateKeyPair generates a new key pair.

func ParsePrivateKey

func ParsePrivateKey(key []byte) (*rsa.PrivateKey, error)

ParsePrivateKey parses private key bytes to *rsa.PrivateKey.

func ParsePublicKey

func ParsePublicKey(key []byte) (*rsa.PublicKey, error)

ParsePublicKey parses public key bytes to *rsa.PublicKey.

Types

type AESOpt

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

AESOpt contains all aes session option

func NewAESOpt

func NewAESOpt(secret string) (*AESOpt, error)

NewAESOpt is function to create new configuration of aes algorithm option the secret must be hexa a-f & 0-9

Example
package main

import (
	"fmt"
	"log"

	"github.com/bingoohuang/gg/pkg/cry"
)

func main() {
	// sample plain text
	sampleText := "Halo this is encrypted text!!!"

	// it's random string must be hexa  a-f & 0-9
	const key = "fa89277fb1e1c344709190deeac4465c2b28396423c8534a90c86322d0ec9dcf"
	// define AES option
	aesOpt, err := cry.NewAESOpt(key)
	if err != nil {
		log.Println("ERR", err)
		return
	}

	// Encrypt text using AES algorithm
	cipherText, err := aesOpt.Encrypt([]byte(sampleText))
	if err != nil {
		log.Println("ERR", err)
		return
	}
	// 每次加密结果不一样(因为加入了随机的nonce)
	// fmt.Println("Encrypted data", string(cipherText))
	// Encrypted data 28509ae15364b3994846eeb4079122825285ac7863f94fab43aacb43b5a81e2f93c58743c5d089ae4fefe468b1e240ac88cb50e9316a2f618d55
	// Encrypted data b91a0019778033730704da5881a39c955f58c878f6a7938da107a2cbb9d752100af56024463d901c75b1ea6cb63089bf88e8b758b9786de9150e

	// Decrypt text using AES algorithm
	plainText, err := aesOpt.Decrypt([]byte(cipherText))
	if err != nil {
		log.Println("ERR", err)
		return
	}
	fmt.Println("Decrypted data", string(plainText))

}
Output:

Decrypted data Halo this is encrypted text!!!

func (*AESOpt) Decrypt

func (aesOpt *AESOpt) Decrypt(chiperText []byte) (string, error)

Decrypt is function to decypt data using AES algorithm

func (*AESOpt) Encrypt

func (aesOpt *AESOpt) Encrypt(plainText []byte) (string, error)

Encrypt is function to encrypt data using AES algorithm

type DESOpt

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

DESOpt contains all DES session option

func NewDESOpt

func NewDESOpt(secret string) (*DESOpt, error)

NewDESOpt is function to create new configuration of des algorithm option the secret must be 24 character

Example
package main

import (
	"fmt"
	"log"

	"github.com/bingoohuang/gg/pkg/cry"
)

func main() {
	// sample plain text
	sampleText := "Halo this is encrypted text!!!"
	// it's character 24 bit
	const key = "123456781234567812345678"
	// define DES option
	desOpt, err := cry.NewDESOpt(key)
	if err != nil {
		log.Println("ERR", err)
		return
	}

	// Encrypt text using DES algorithm
	cipherText, err := desOpt.Encrypt([]byte(sampleText))
	if err != nil {
		log.Println("ERR", err)
		return
	}
	// fmt.Println("Encrypted data:", cipherText)
	// 每次都得到一样的数据
	// Encrypted data: k1Uoi4OsCMBSCeVxdBmwfVuO2PxndJZSfCsXIULB7F0=

	// Decrypt text using DES algorithm
	plainText, err := desOpt.Decrypt([]byte(cipherText))
	if err != nil {
		log.Println("ERR", err)
		return
	}
	fmt.Println("Decrypted data:", plainText)
}
Output:

Decrypted data: Halo this is encrypted text!!!

func (*DESOpt) Decrypt

func (desOpt *DESOpt) Decrypt(chiperText []byte) (string, error)

Decrypt is function to decypt data using DES algorithm

func (*DESOpt) Encrypt

func (desOpt *DESOpt) Encrypt(plainText []byte) (string, error)

Encrypt is function to encrypt data using DES algorithm

type GocryptInterface

type GocryptInterface interface {
	Encrypt(interface{}) error
	Decrypt(interface{}) error
}

GocryptInterface is facing the format gocrypt option library

type GocryptOption

type GocryptOption interface {
	Encrypt(plainText []byte) (string, error)
	Decrypt(chipherText []byte) (string, error)
}

GocryptOption is facing the format encryption and decryption format

type Option

type Option struct {
	AESOpt  GocryptOption
	DESOpt  GocryptOption
	RC4Opt  GocryptOption
	Custom  map[string]GocryptOption
	Prefix  string
	Postfix string
}

Option contains an option from initial algorithm encryptioin & decryption.

func New

func New(opt *Option) *Option

New create and initialize new option for struct field encryption.

It needs option from aes, rc4, or des for initialitaion

func (*Option) Decrypt

func (opt *Option) Decrypt(structVal interface{}) error

Decrypt is function to set struct field decrypted

func (*Option) Encrypt

func (opt *Option) Encrypt(structVal interface{}) error

Encrypt is function to set struct field encrypted

type RC4Opt

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

RC4Opt is tructure of aes option

func NewRC4Opt

func NewRC4Opt(secret string) (*RC4Opt, error)

NewRC4Opt is function to create new configuration of aes algorithm option the secret must be hexa a-f & 0-9

Example
package main

import (
	"fmt"
	"log"

	"github.com/bingoohuang/gg/pkg/cry"
)

func main() {
	// sample plain text
	sampleText := "Halo this is encrypted text!!!"
	// it's character 24 bit
	const key = "123456781234567812345678"
	// define RC4 option
	rc4Opt, err := cry.NewRC4Opt(key)
	if err != nil {
		log.Println("ERR", err)
		return
	}

	// Encrypt text using RC4 algorithm
	cipherText, err := rc4Opt.Encrypt([]byte(sampleText))
	if err != nil {
		log.Println("ERR", err)
		return
	}
	// fmt.Println("Encrypted data:", cipherText)
	// 每次都得到一样的数据
	// Encrypted data: f39255bb29c5b6ce831363bc865866c600e7ed3dac0c5dc13c63a196788c

	// Decrypt text using RC4 algorithm
	plainText, err := rc4Opt.Decrypt([]byte(cipherText))
	if err != nil {
		log.Println("ERR", err)
		return
	}
	fmt.Println("Decrypted data:", plainText)
}
Output:

Decrypted data: Halo this is encrypted text!!!

func (*RC4Opt) Decrypt

func (rc4Opt *RC4Opt) Decrypt(disini []byte) (string, error)

Decrypt decrypts the first block in src into dst. Dst and src may point at the same memory.

func (*RC4Opt) Encrypt

func (rc4Opt *RC4Opt) Encrypt(src []byte) (string, error)

Encrypt encrypts the first block in src into dst. Dst and src may point at the same memory.

Jump to

Keyboard shortcuts

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