PureBasic
PureBasic
Generate an RSA Key and Get as Base64 DER
See more RSA Examples
Demonstrates how to generate a 2048-bit RSA key and return the public and private parts as unencrypted Base64 encoded DER.Chilkat PureBasic Downloads
IncludeFile "CkPublicKey.pb"
IncludeFile "CkPrivateKey.pb"
IncludeFile "CkRsa.pb"
Procedure ChilkatExample()
success.i = 0
; This example assumes the Chilkat API to have been previously unlocked.
; See Global Unlock Sample for sample code.
rsa.i = CkRsa::ckCreate()
If rsa.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Generate a 2048-bit key.
privKey.i = CkPrivateKey::ckCreate()
If privKey.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkRsa::ckGenKey(rsa,2048,privKey)
If success = 0
Debug CkRsa::ckLastErrorText(rsa)
CkRsa::ckDispose(rsa)
CkPrivateKey::ckDispose(privKey)
ProcedureReturn
EndIf
; Get the public part of the key.
pubKey.i = CkPublicKey::ckCreate()
If pubKey.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkPrivateKey::ckToPublicKey(privKey,pubKey)
; There are two possible formats for representing the RSA public key
; in ASN.1 (DER). The possible formats are PKCS1 and PKCS8.
; We can get either by setting bChoosePkcs1 to 1 or 0.
bChoosePkcs1.i = 1
pubKeyBase64Der.s = CkPublicKey::ckGetEncoded(pubKey,bChoosePkcs1,"base64")
Debug "Public Key Base64 DER:"
Debug pubKeyBase64Der
; Get the private key as Base64 DER:
; We can get PKCS1 or PKCS8, but with different methods:
privKeyPkcs1.s = CkPrivateKey::ckGetPkcs1ENC(privKey,"base64")
Debug "Private Key PKCS1 Base64 DER:"
Debug privKeyPkcs1
privKeyPkcs8.s = CkPrivateKey::ckGetPkcs8ENC(privKey,"base64")
Debug "Private Key PKCS8 Base64 DER:"
Debug privKeyPkcs8
CkRsa::ckDispose(rsa)
CkPrivateKey::ckDispose(privKey)
CkPublicKey::ckDispose(pubKey)
ProcedureReturn
EndProcedure