Golang : Encrypt and decrypt data with x509 crypto
This is a simple tutorial demonstrating how to encrypt and decrypt string data with Golang's crypto/x509
package. We will use the EncryptPEMBlock and DecryptPEMBlock functions.
The source code :
package main
import (
"fmt"
"crypto/rand"
"crypto/x509"
"os"
)
func main() {
blockType := "RSA PRIVATE KEY"
password := []byte("password")
// see http://golang.org/pkg/crypto/x509/#pkg-constants
cipherType := x509.PEMCipherAES256
EncryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
blockType,
[]byte("secret message"),
password,
cipherType)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// check if encryption is successful or not
if !x509.IsEncryptedPEMBlock(EncryptedPEMBlock) {
fmt.Println("PEM Block is not encrypted!")
os.Exit(1)
}
if EncryptedPEMBlock.Type != blockType {
fmt.Println("Block type is wrong!")
os.Exit(1)
}
fmt.Printf("Encrypted block \n%v\n", EncryptedPEMBlock)
fmt.Printf("Encrypted Block Headers Info : %v\n", EncryptedPEMBlock.Headers)
DecryptedPEMBlock, err := x509.DecryptPEMBlock(EncryptedPEMBlock, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Decrypted block message is : \n%s\n", DecryptedPEMBlock)
}
Sample output :
Encrypted block &{RSA PRIVATE KEY map[Proc-Type:4,ENCRYPTED DEK-Info:AES-256-CBC,9f08b2afcf44a3115f8eacc78600a108] [133 90 249 15 68 167 149 212 114 250 51 248 47 5 137 144]}
Encrypted Block Headers Info : map[Proc-Type:4,ENCRYPTED DEK-Info:AES-256-CBC,9f08b2afcf44a3115f8eacc78600a108]
Decrypted block message is : secret message
See also : Golang : Create x509 certificate, private and public keys
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.8k Golang : calculate elapsed run time
+11.7k Golang : convert(cast) string to integer value
+24.7k Golang : Convert uint value to string type
+30.3k error: trying to remove "yum", which is protected
+15.6k Golang : convert string or integer to big.Int type
+22k Golang : untar or extract tar ball archive example
+11.7k Golang : Print UTF-8 fonts on image example
+9.5k Golang : Convert octal value to string to deal with leading zero problem
+12.4k Golang : Convert IPv4 address to packed 32-bit binary format
+6.5k Golang : Get Alexa ranking data example
+11.7k Golang : Get month name from date example
+10.6k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example