Go
Go
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.Chilkat Go Downloads
success := false
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// First generate a 256-bit AES key (32 bytes).
prng := chilkat.NewPrng()
bdAesKey := chilkat.NewBinData()
success = prng.GenRandomBd(32,bdAesKey)
// Use a public key from a certificate for RSA encryption.
cert := chilkat.NewCert()
success = cert.LoadFromFile("qa_data/pem/mf_public_rsa.pem")
if success == false {
fmt.Println(cert.LastErrorText())
prng.DisposePrng()
bdAesKey.DisposeBinData()
cert.DisposeCert()
return
}
pubKey := chilkat.NewPublicKey()
cert.GetPublicKey(pubKey)
rsa := chilkat.NewRsa()
success = rsa.UsePublicKey(pubKey)
if success == false {
fmt.Println(rsa.LastErrorText())
prng.DisposePrng()
bdAesKey.DisposeBinData()
cert.DisposeCert()
pubKey.DisposePublicKey()
rsa.DisposeRsa()
return
}
// RSA encrypt our 32-byte AES key.
// The contents of bdAesKey are replaced with result of the RSA encryption.
success = rsa.EncryptBd(bdAesKey,false)
if success == false {
fmt.Println(rsa.LastErrorText())
prng.DisposePrng()
bdAesKey.DisposeBinData()
cert.DisposeCert()
pubKey.DisposePublicKey()
rsa.DisposeRsa()
return
}
// Return the result as a base64 string
encryptedAesKey := bdAesKey.GetEncoded("base64")
fmt.Println("encrypted AES key = ", *encryptedAesKey)
prng.DisposePrng()
bdAesKey.DisposeBinData()
cert.DisposeCert()
pubKey.DisposePublicKey()
rsa.DisposeRsa()