Sample code for 30+ languages & platforms
PowerBuilder

RSA Encrypt and Decrypt Credit Card Numbers

See more RSA Examples

_LANGUAGE_ sample code to RSA public-key encrypt and decrypt credit card numbers. The RSA key is loaded from an unencrypted PKCS8 file. Chilkat provides many ways of setting the key -- loading from both encrypted and unencrypted PEM, PKCS8, DER, PVK, etc. Keys may be loaded from files or in-memory representations. (The RSA component also provides the ability to generate RSA keys.)

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Rsa
oleobject loo_PrivKey
oleobject loo_PubKey
string ls_CcNumber
integer li_UsePrivateKey
string ls_EncryptedStr
oleobject loo_RsaDecryptor
string ls_DecryptedStr

li_Success = 0

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

loo_Rsa = create oleobject
li_rc = loo_Rsa.ConnectToNewObject("Chilkat.Rsa")
if li_rc < 0 then
    destroy loo_Rsa
    MessageBox("Error","Connecting to COM object failed")
    return
end if

loo_PrivKey = create oleobject
li_rc = loo_PrivKey.ConnectToNewObject("Chilkat.PrivateKey")

// Load an RSA private key from a file:
li_Success = loo_PrivKey.LoadAnyFormatFile("rsaPrivateKey.key","")
if li_Success = 0 then
    Write-Debug loo_PrivKey.LastErrorText
    destroy loo_Rsa
    destroy loo_PrivKey
    return
end if

// Get the public part of the private key.
loo_PubKey = create oleobject
li_rc = loo_PubKey.ConnectToNewObject("Chilkat.PublicKey")

loo_PrivKey.ToPublicKey(loo_PubKey)

li_Success = loo_Rsa.UsePublicKey(loo_PubKey)
if li_Success = 0 then
    Write-Debug loo_Rsa.LastErrorText
    destroy loo_Rsa
    destroy loo_PrivKey
    destroy loo_PubKey
    return
end if

// Encrypt a VISA credit card number:
// 1234-5678-0000-9999
ls_CcNumber = "1234567800009999"

li_UsePrivateKey = 0
loo_Rsa.EncodingMode = "base64"
ls_EncryptedStr = loo_Rsa.EncryptStringENC(ls_CcNumber,li_UsePrivateKey)
Write-Debug "Encrypted:"
Write-Debug ls_EncryptedStr

// Now decrypt:
loo_RsaDecryptor = create oleobject
li_rc = loo_RsaDecryptor.ConnectToNewObject("Chilkat.Rsa")

loo_RsaDecryptor.EncodingMode = "base64"
loo_RsaDecryptor.UsePrivateKey(loo_PrivKey)

li_UsePrivateKey = 1
ls_DecryptedStr = loo_RsaDecryptor.DecryptStringENC(ls_EncryptedStr,li_UsePrivateKey)

Write-Debug "Decrypted:"
Write-Debug ls_DecryptedStr

// Important: RSA encryption should only be used to encrypt small amounts of data.
// It is typically used for encrypting symmetric encryption
// keys such that a symmetric encryption algorithm, such as 
// AES is then used to encrypt/decrypt bulk data


destroy loo_Rsa
destroy loo_PrivKey
destroy loo_PubKey
destroy loo_RsaDecryptor