How to use createHMAC method of crypto Package

Best K6 code snippet using crypto.createHMAC

crypto.go

Source:crypto.go Github

copy

Full Screen

1package crypto2import (3 "crypto/aes"4 "crypto/cipher"5 "crypto/hmac"6 "crypto/rand"7 "crypto/sha512"8 "encoding/base64"9 "fmt"10 "io"11 "io/ioutil"12 "log"13 "os"14 "regexp"15 "strings"16 "syscall"17 "golang.org/x/crypto/ssh/terminal"18)19var (20 wrappedCipherRegex = regexp.MustCompile(`@encrypted_data\((.*)\)`)21 wrappedHmacRegex = regexp.MustCompile(`@hmac\((.*)\)`)22)23// EncryptionObject contains all the variables and methods24// associated with encrypting and decrypting data25type EncryptionObject struct {26 Key []byte27 CipherText []byte28 PlainText []byte29 HMAC []byte30 WrappedData string31}32// Encrypt will crypto data with specified key33func (e *EncryptionObject) Encrypt() error {34 block, err := aes.NewCipher(e.Key)35 if err != nil {36 return fmt.Errorf("Error creating AES block: %v", err)37 }38 e.CipherText = make([]byte, aes.BlockSize+len(e.PlainText))39 iv := e.CipherText[:aes.BlockSize]40 if _, err := io.ReadFull(rand.Reader, iv); err != nil {41 return fmt.Errorf("Error creating iv: %v", err)42 }43 stream := cipher.NewCFBEncrypter(block, iv)44 stream.XORKeyStream(e.CipherText[aes.BlockSize:], e.PlainText)45 e.HMAC, err = CreateHMAC(e.Key, e.CipherText)46 if err != nil {47 return fmt.Errorf("Creating HMAC: %v", err)48 }49 e.WrapCrypto()50 return nil51}52// Decrypt will decrypt data with specified key53func (e *EncryptionObject) Decrypt() error {54 h, _ := CreateHMAC(e.Key, e.CipherText)55 if !hmac.Equal(e.HMAC, h) {56 return fmt.Errorf("HMAC failure, ciphertext has changed, this could indicate incorrect key")57 }58 block, err := aes.NewCipher(e.Key)59 if err != nil {60 return fmt.Errorf("Error creating AES block: %v", err)61 }62 iv := e.CipherText[:aes.BlockSize]63 e.CipherText = e.CipherText[aes.BlockSize:]64 e.PlainText = make([]byte, len(e.CipherText))65 stream := cipher.NewCFBDecrypter(block, iv)66 stream.XORKeyStream(e.PlainText, e.CipherText)67 return nil68}69// CreateHMAC will generate a cryptographic hash of data supplied70func CreateHMAC(keyb []byte, data []byte) ([]byte, error) {71 h := hmac.New(sha512.New, keyb)72 _, err := h.Write(data)73 if err != nil {74 return nil, fmt.Errorf("Error writing data for HMAC: %v", err)75 }76 return h.Sum(nil), nil77}78// WrapCrypto wraps both cipher text and hmac into a single string79// to be written to disk80func (e *EncryptionObject) WrapCrypto() {81 b64cipher := base64.StdEncoding.EncodeToString(e.CipherText)82 b64hmac := base64.StdEncoding.EncodeToString(e.HMAC)83 e.WrappedData = fmt.Sprintf("@encrypted_data(%s)\n@hmac(%s)", b64cipher, b64hmac)84}85//UnwrapCrypto unwraps cipher text and hmac to allow decryption86func (e *EncryptionObject) UnwrapCrypto() error {87 var err error88 b64cipher := wrappedCipherRegex.FindStringSubmatch(e.WrappedData)89 if b64cipher == nil || len(b64cipher) < 1 || b64cipher[1] == "" {90 return fmt.Errorf("unwrapping cipher text")91 }92 e.CipherText, err = base64.StdEncoding.DecodeString(b64cipher[1])93 if err != nil {94 return fmt.Errorf("decoding base64 cipher: %v", err)95 }96 b64hmac := wrappedHmacRegex.FindStringSubmatch(e.WrappedData)97 if b64hmac == nil || len(b64hmac) < 1 || b64hmac[1] == "" {98 return fmt.Errorf("unwrapping HMAC text")99 }100 e.HMAC, err = base64.StdEncoding.DecodeString(b64hmac[1])101 if err != nil {102 return fmt.Errorf("decoding base64 HMAC: %v", err)103 }104 return nil105}106// RandomKey returns a number of random bytes107func RandomKey(n int) []byte {108 b := make([]byte, n)109 rand.Reader.Read(b)110 return b111}112// RandomKeyB64 is the same as RandomKey but returns the bytes encoded in Base64113func RandomKeyB64(n int) string {114 b := make([]byte, n)115 rand.Reader.Read(b)116 return base64.StdEncoding.EncodeToString(b)117}118func (e *EncryptionObject) ReadConfigFiles(filename string) []byte {119 var (120 file []byte121 err error122 )123 if filename != "" {124 file, err = ioutil.ReadFile(filename)125 if err != nil {126 log.Fatal("Error reading file: ", err)127 }128 } else {129 pwd, err := os.Getwd()130 if err != nil {131 log.Fatalf("Error getting working directory: %v", err)132 }133 files, err := ioutil.ReadDir(pwd)134 if err != nil {135 log.Fatalf("Error reading directory: %v", err)136 }137 for _, f := range files {138 if !f.IsDir() && strings.HasSuffix(f.Name(), ".vc") {139 fbytes, err := ioutil.ReadFile(f.Name())140 if err != nil {141 log.Fatalf("Error reading file: %v", err)142 }143 file = JoinBytes(fbytes, file)144 }145 }146 }147 return file148}149func (e *EncryptionObject) ReadEncryptedConfigFiles(filename string) []byte {150 var (151 file []byte152 err error153 )154 pwd, err := os.Getwd()155 if err != nil {156 log.Fatalf("Error getting working directory: %v", err)157 }158 files, err := ioutil.ReadDir(pwd)159 if err != nil {160 log.Fatalf("Error reading directory: %v", err)161 }162 for _, f := range files {163 if !f.IsDir() && strings.HasSuffix(f.Name(), ".vc.enc") {164 fbytes, err := ioutil.ReadFile(f.Name())165 if err != nil {166 log.Fatalf("Error reading file: %v", err)167 }168 e.WrappedData = string(fbytes)169 if err := e.UnwrapCrypto(); err != nil {170 log.Fatalf("Error unwrapping encrypted file: %v\nErr: %v", f.Name(), err)171 }172 if err := e.Decrypt(); err != nil {173 log.Fatalf("Error decrypting file: %v\n Err: %v", f.Name(), err)174 }175 file = JoinBytes([]byte(e.PlainText), file)176 }177 }178 return file179}180func EncryptString(data string, key []byte) (string, error) {181 e := EncryptionObject{182 Key: key,183 PlainText: []byte(data),184 }185 block, err := aes.NewCipher(e.Key)186 if err != nil {187 return "", fmt.Errorf("Error creating AES block: %v", err)188 }189 e.CipherText = make([]byte, aes.BlockSize+len(e.PlainText))190 iv := e.CipherText[:aes.BlockSize]191 if _, err := io.ReadFull(rand.Reader, iv); err != nil {192 return "", fmt.Errorf("Error creating iv: %v", err)193 }194 stream := cipher.NewCFBEncrypter(block, iv)195 stream.XORKeyStream(e.CipherText[aes.BlockSize:], e.PlainText)196 e.HMAC, err = CreateHMAC(e.Key, e.CipherText)197 e.WrapCrypto()198 return fmt.Sprintf("@encrypted_data(%s)", base64.StdEncoding.EncodeToString([]byte(e.WrappedData))), nil199}200func DecryptString(WrappedText string, key []byte) (string, error) {201 var err error202 e := EncryptionObject{203 Key: key,204 }205 b64wt := wrappedCipherRegex.FindStringSubmatch(WrappedText)206 if b64wt == nil || len(b64wt) < 1 || b64wt[1] == "" {207 return "", fmt.Errorf("unwrapping cipher text")208 }209 b64wrap, err := base64.StdEncoding.DecodeString(b64wt[1])210 if err != nil {211 return "", fmt.Errorf("decoding base64 cipher: %v", err)212 }213 e.WrappedData = string(b64wrap)214 e.UnwrapCrypto()215 h, _ := CreateHMAC(e.Key, e.CipherText)216 if !hmac.Equal(e.HMAC, h) {217 return "", fmt.Errorf("HMAC failure, ciphertext has changed, this could indicate incorrect key")218 }219 block, err := aes.NewCipher(e.Key)220 if err != nil {221 return "", fmt.Errorf("Error creating AES block: %v", err)222 }223 iv := e.CipherText[:aes.BlockSize]224 e.CipherText = e.CipherText[aes.BlockSize:]225 e.PlainText = make([]byte, len(e.CipherText))226 stream := cipher.NewCFBDecrypter(block, iv)227 stream.XORKeyStream(e.PlainText, e.CipherText)228 return string(e.PlainText), nil229}230func JoinBytes(dst, src []byte) []byte {231 for _, b := range src {232 dst = append(dst, b)233 }234 dst = append(dst, byte(10))235 return dst236}237func GetPassword() ([]byte, error) {238 fmt.Print("Please enter encryption key: ")239 bytesB64Key, err := terminal.ReadPassword(int(syscall.Stdin))240 if err != nil {241 return nil, fmt.Errorf("Error reading encryption key from terminal: %v", err)242 }243 bytesKey, err := base64.StdEncoding.DecodeString(string(bytesB64Key))244 if err != nil {245 return nil, fmt.Errorf("Error decoding base64 key: %v", err)246 }247 return bytesKey, nil248}...

Full Screen

Full Screen

hmac.go

Source:hmac.go Github

copy

Full Screen

...8)9func main() {10 message := []byte("Hello World!")11 key := []byte("My $3cr3t k3y")12 messageMAC := createHMAC(message, key)13 if checksum, ok := checkMAC(message, messageMAC, key); ok {14 fmt.Printf("Ok!\nMessage: %s\nChecksum: %x\n", string(message), checksum)15 } else {16 fmt.Println("Checksum error!")17 }18}19// createHMAC function return a SHA256 hash using a message and a key.20func createHMAC(message, key []byte) []byte {21 hash := hmac.New(sha256.New, key)22 hash.Write(message)23 return hash.Sum(nil)24}25// checkMAC function verifies the hash by recomputing it using the same key.26func checkMAC(message, messageMAC, key []byte) ([]byte, bool) {27 hash := hmac.New(sha256.New, key)28 hash.Write(message)29 expectedMAC := hash.Sum(nil)30 return expectedMAC, hmac.Equal(messageMAC, expectedMAC)31}...

Full Screen

Full Screen

createHMAC

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 createHMAC()5 verifyHMAC()6 encryptAES()7 decryptAES()8}9func createHMAC() {10 key := []byte("this is a key")11 h := hmac.New(sha256.New, key)12 h.Write([]byte("this is a message"))13 fmt.Println("HMAC: ", hex.EncodeToString(h.Sum(nil)))14}15func verifyHMAC() {16 key := []byte("this is a key")17 h := hmac.New(sha256.New, key)18 h.Write([]byte("this is a message"))19 fmt.Println("HMAC: ", hex.EncodeToString(h.Sum(nil)))20 sig := h.Sum(nil)21 fmt.Println("Signature: ", sig)22 fmt.Println("Signature: ", hex.EncodeToString(sig))23 h.Reset()24 h.Write([]byte("this is a message"))25 fmt.Println("HMAC: ", hex.EncodeToString(h.Sum(nil)))26 fmt.Println("Signature: ", h.Sum(nil))27 fmt.Println("Signature: ", hex.EncodeToString(h.Sum(nil)))28 fmt.Println("Signature: ", sig)29 fmt.Println("Signature: ", hex.EncodeToString(sig))30 if hmac.Equal(sig, h.Sum(nil)) {31 fmt.Println("Signature is valid.")32 } else {33 fmt.Println("Signature is not valid.")34 }35}36func encryptAES() {37 key := []byte("this is a key")38 plaintext := []byte("this is a message")39 block, err := aes.NewCipher(key)40 if err != nil {41 panic(err)42 }43 gcm, err := cipher.NewGCM(block)44 if err != nil {45 panic(err)46 }47 nonce := make([]byte, gcm.NonceSize())48 if _, err = io.ReadFull(rand.Reader, nonce); err != nil {49 panic(err)50 }51 ciphertext := gcm.Seal(nonce, nonce,

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful