B4J Tutorial B4J: Using RSA with OpenSSL & php

Here's an example B4J app which

- creates RSA Keys
- send the public key to a php script with a message
- the php will encrypt/decrypt/Send the server's keys
- concert/load the server's keys to see if it's compatible
- do an en-/decryption with the server's keys to check compatibility

This B4J-App uses 99.9% of the code of the B4A-APP in this thread: https://www.b4x.com/android/forum/threads/using-rsa-in-b4a-to-communicate-with-php-openssl.59445/

For the php scripts see the thread, too...
 

Attachments

  • RSAExampleB4J.zip
    3.2 KB · Views: 388

ziomorgan

Active Member
Licensed User
Longtime User
I have to decipher a tax code with a certificate X509.
I tried to follow your tutorial but I get the string is not properly decrypted.
Here the code I use.
B4X:
Sub Encrypt_CF(CodFis As String) As String
  Dim ForeignKPG As KeyPairGenerator
  Dim c As Cipher
  Dim su As StringUtils
  Dim Bconv As ByteConverter
   
  Dim ForeignPubKeyString As String
  Dim ForeignPubKeyBytes(0) As Byte
   
  Dim MessageBytes(0),MessageBytesEncrypted(0) As Byte
  Dim MessageStringEncrypted As String
   
  c.Initialize("RSA/ECB/PKCS1Padding")
  ForeignKPG.Initialize("RSA", 2048)
  ForeignPubKeyString = File.ReadString("C:\OpenSSL\bin", "test.crt").Trim
   
  ForeignPubKeyBytes = su.DecodeBase64(ForeignPubKeyString)
  ForeignPubKeyString = Bconv.StringFromBytes(ForeignPubKeyBytes, "UTF8")

  ForeignPubKeyString = ForeignPubKeyString.Replace("-----BEGIN PUBLIC KEY-----","")
  ForeignPubKeyString = ForeignPubKeyString.Replace("-----END PUBLIC KEY-----","")
   
  ForeignPubKeyBytes = su.DecodeBase64(ForeignPubKeyString)
   
  ForeignKPG.publicKeyFromBytes(ForeignPubKeyBytes)
   
  MessageBytes = Bconv.StringToBytes(CodFis, "UTF8")
   
  MessageBytesEncrypted = c.encrypt(MessageBytes, ForeignKPG.PublicKey, False)
   
  MessageStringEncrypted = Bconv.HexFromBytes(MessageBytesEncrypted)
  MessageStringEncrypted = su.EncodeBase64(MessageBytesEncrypted)
   
   Log(MessageStringEncrypted)
   
  Return MessageStringEncrypted
End Sub

Can you help me find where is the error?
Thank you
 
Top