To decrypt data using symmetric key cryptography in Go, you can use the crypto/aes
package. Here's an example code that demonstrates the decryption process:
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func main() {
key := []byte("0123456789abcdef") // 16-byte symmetric key
// Example ciphertext
ciphertext := []byte{129, 254, 8, 35, 35, 232, 122, 62, 31, 46, 212, 201, 225, 195, 172, 112}
// Create the AES cipher block
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// Create a new CBC mode decrypter
iv := []byte("initializationvec") // 16-byte initialization vector
decrypter := cipher.NewCBCDecrypter(block, iv)
// Create a buffer for storing the decrypted data
plaintext := make([]byte, len(ciphertext))
// Decrypt the data
decrypter.CryptBlocks(plaintext, ciphertext)
// Remove padding (if any) from the plaintext
unpaddedPlaintext := unpadPKCS7(plaintext)
fmt.Printf("Decrypted data: %s\n", string(unpaddedPlaintext))
}
// PKCS7 unpadding function
func unpadPKCS7(data []byte) []byte {
padding := data[len(data)-1]
return data[:len(data)-int(padding)]
}
Make sure to replace the key
, ciphertext
, and iv
variables with your own values. The example code above assumes you are using CBC mode and a PKCS7 padding scheme. You may need to change the padding scheme and block mode based on your requirements.
Note: It's important to handle errors and use proper error handling measures in production code.