乐闻世界logo
搜索文章和话题

How do you use the " crypto " package to perform cryptographic operations in Go?

1个答案

1

In Go, the crypto package and its sub-packages provide a comprehensive set of encryption functionalities, including common algorithms such as AES and RSA. Here, I will demonstrate a detailed example of how to use the Go crypto package for AES encryption operations.

Steps for AES Encryption

  1. Selecting the Appropriate Encryption Mode: AES supports multiple modes, including CBC, CFB, and ECB. For this example, we use CBC mode.
  2. Generating the Key: AES encryption requires keys of 128, 192, or 256 bits in length. The key must be randomly generated to ensure security.
  3. Creating the Cipher: Based on the selected mode and key, instantiate the corresponding cipher.
  4. Preparing Input Data: Before encryption, apply padding (Padding) to ensure the data length aligns with the algorithm's requirements.
  5. Performing Encryption: Use the cipher to encrypt the data.
  6. Handling Output: The encrypted data is typically stored in binary format and can be converted to formats like Base64 as needed.

Example Code

Below is the Go code demonstrating AES encryption in CBC mode:

go
package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" ) func main() { // Original text text := "Hello, World! This is a secret message." // Key (256 bits) key := []byte("32-byte-long-key-1234567890123456") // Encrypted text encryptedText, err := encrypt(text, key) if err != nil { panic(err) } fmt.Printf("Encrypted: %s\n", encryptedText) // Decrypted text decryptedText, err := decrypt(encryptedText, key) if err != nil { panic(err) } fmt.Printf("Decrypted: %s\n", decryptedText) } // Encryption function func encrypt(plainText string, key []byte) (string, error) { block, err := aes.NewCipher(key) if err != nil { return "", err } plainTextBytes := []byte(plainText) blockSize := block.BlockSize() plainTextBytes = PKCS7Padding(plainTextBytes, blockSize) cipherText := make([]byte, blockSize+len(plainTextBytes)) iv := cipherText[:blockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", err } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(cipherText[blockSize:], plainTextBytes) return base64.URLEncoding.EncodeToString(cipherText), nil } // Decryption function func decrypt(cipherText string, key []byte) (string, error) { block, err := aes.NewCipher(key) if err != nil { return "", err } cipherTextBytes, err := base64.URLEncoding.DecodeString(cipherText) if err != nil { return "", err } if len(cipherTextBytes) < block.BlockSize() { return "", fmt.Errorf("cipherText too short") } iv := cipherTextBytes[:block.BlockSize()] cipherTextBytes = cipherTextBytes[block.BlockSize():] mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(cipherTextBytes, cipherTextBytes) cipherTextBytes = PKCS7UnPadding(cipherTextBytes) return string(cipherTextBytes), nil } // Padding function func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } // UnPadding function func PKCS7UnPadding(plantText []byte) []byte { length := len(plantText) unpadding := int(plantText[length-1]) return plantText[:(length - unpadding)] }

This example covers the encryption and decryption processes, along with PKCS7 padding and unpadding. It clearly illustrates how to use the crypto package in Go for AES encryption operations.

2024年8月7日 17:39 回复

你的答案