[Gambas-user] Can I encrypt a string

Tobias Boege taboege at gmail.com
Sat Jul 6 21:51:49 CEST 2019


On Tue, 02 Jul 2019, Mayost Sharon wrote:
> hello
> 
> Can I encrypt a string
> 
> Such as PHP
> $plaintext = "my string sharon";
> $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
> $key = "mykey12345678";
> $iv = openssl_random_pseudo_bytes($ivlen);
> $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA,
> $iv);
> $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
> $ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
> 

I just added the two missing features to gb.openssl that prevented the above
from being transcribed to Gambas:

  (1) Passing arbitrary digest methods to HMac() is now possible,
  (2) Random strings can be generated now by OpenSSL.RandomBytes.

If you use the master branch (will probably land in Gambas 3.14), you can now
write:

  Public Sub Main()
    ' $plaintext = "my string sharon";
    Dim plain As String = "my string sharon"

    ' $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
    Dim ivlen As Integer = Cipher["AES-128-CBC"].IvLength

    ' $key = "mykey12345678";
    Dim key As String = "mykey12345678\0\0\0" ' key length has to match Cipher[].KeyLength, I padded it with NULs

    ' $iv = openssl_random_pseudo_bytes($ivlen);
    Dim iv As String = OpenSSL.RandomBytes(ivlen)

    ' $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
    Dim ciphertext_raw As CipherText = Cipher["AES-128-CBC"].Encrypt(plain, key, iv)

    ' $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
    Dim mac As String = HMac(key, ciphertext_raw.Cipher, "sha256")

    ' $ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
    Dim ciphertext As String = Base64$(iv & mac & ciphertext_raw.Cipher)

    Print ciphertext
  End

Sample output:

  60AuJch4tam0f9hmRz9gYYlSdyvfsvMoVLlbEt0aHy7hJycxGWf/mBAlHBjkGE0HiVJ3K9+y8yhUuVsS3RofLuEnJzEZZ/+YECUcGOQYTQc=

Regards,
Tobi

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk


More information about the User mailing list