Sample code for 30+ languages & platforms
PureBasic

Generate an RSA Key and Save to Encrypted PEM

See more RSA Examples

Demonstrates how to generate an RSA key and save to an encrypted PEM file.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkPublicKey.pb"
IncludeFile "CkPrivateKey.pb"
IncludeFile "CkRsa.pb"

Procedure ChilkatExample()

    success.i = 0

    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

    password.s = "secret"
    ; Saving to a relative path (from the current working directory of the process).
    path.s = "rsaKeys/myTestRsaPrivate.pem"
    ; Encrypt the PEM using 256-bit AES encryption.
    CkPrivateKey::setCkPkcs8EncryptAlg(privKey, "aes256")
    success = CkPrivateKey::ckSavePkcs8EncryptedPemFile(privKey,password,path)
    If success = 0
        Debug CkPrivateKey::ckLastErrorText(privKey)
        CkRsa::ckDispose(rsa)
        CkPrivateKey::ckDispose(privKey)
        ProcedureReturn
    EndIf

    ; image

    ; We can also save the public key.
    ; There is no need to encrypt public keys.
    pubKey.i = CkPublicKey::ckCreate()
    If pubKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkPrivateKey::ckToPublicKey(privKey,pubKey)

    path = "rsaKeys/myTestRsaPublic.pem"
    ; Choose PKCS1 or PKCS8
    ; We'll choose PKCS8.
    preferPkcs1.i = 0
    success = CkPublicKey::ckSavePemFile(pubKey,preferPkcs1,path)
    If success = 0
        Debug CkPublicKey::ckLastErrorText(pubKey)
        CkRsa::ckDispose(rsa)
        CkPrivateKey::ckDispose(privKey)
        CkPublicKey::ckDispose(pubKey)
        ProcedureReturn
    EndIf

    ; image

    Debug "Success."


    CkRsa::ckDispose(rsa)
    CkPrivateKey::ckDispose(privKey)
    CkPublicKey::ckDispose(pubKey)


    ProcedureReturn
EndProcedure