Android Question Saving RSA Generated Key Into KeyStore

Klaas Tijsen

New Member
Licensed User
Hello, I'm Kinda New To B4a and for sure using Keystore. (never used before) I'm having a problem where I'm trying to save the new generated pair of RSA, 2048 keys into the KeyStore of where I believe that used to keep the private key safe, and constant where the public key can be saved on a server, in order to send encrypted messages using the public key, im not to sure if this even the correct/ most effective way to do this.

B4X:
ks.Initialize("Keystore")
    Log(ks.Aliases)
    
   
    Dim kpg As KeyPairGenerator
    Dim Enc As Cipher
    Enc.Initialize("RSA/ECB/PKCS1Padding")
    kpg.Initialize("RSA",2048)
    
    kpg.GenerateKey
    
    
   'this part throws the error
    ks.setEntry2("DonMan",kpg.PrivateKeyToBytes,ks.getCertificateChain("DonMan"))
    
    Dim Text As String = "Hello World"
    
    Dim su As StringUtils
    Dim bytes() As Byte = Text.GetBytes("UTF8")
    
    Log(su.EncodeBase64(kpg.PrivateKeyToBytes))

    Dim encryptedstring As String = su.EncodeBase64(Enc.Encrypt(bytes,kpg.PublicKey,False))
    Log(encryptedstring)
    
    Dim bc As ByteConverter
    Log( bc.StringFromBytes(Enc.Decrypt(su.DecodeBase64(encryptedstring),kpg.PrivateKey,False),"UTF8"))

the part that throws an error that the ks.getCertificateChain("DonMan") is null, is there something else i needed to do? or is this completely wrong
 

KMatle

Expert
Licensed User
A certificate is much more complex as just the private/public key. Chaining means that you need a real certificate from an official issuer (which is a trusted authority -> meaning of trust chain).

However: What are you going to achieve? Just exchanging encrypted messages? Then you don't need the keystore. Store the private/public key in a file (I use maps to do so).
 
Upvote 0
Top