1

I have a public key (RSA) as a string. I want to use this key to create a secret code, lets say the unencrypted secret code is "TEST TEST" without qoutes.

How can this be achieved? I mean I tried the following but stuck on creating the Key object from the public key string I used nimbus-jose-jwt library. But wasn't able to create RSA public key object in the following code

// Create the header
        val header = JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A256CBC_HS512)

// Set the plain text
        val payload = Payload(decryptedText)

// Create the JWE object and encrypt it
        val jweObject = JWEObject(header, payload)

        jweObject.encrypt(JWEEncrypter)

// Serialise to compact JOSE form...
        val actual = jweObject.serialize()

Also I used another library named org.bitbucket.b_c:jose4j but same thing, I wasn't able to successfully create public key object from the public key string that I got.

Here is the code snippet that I used but failed to achieve what I want and be able to correctly encrypt TEST TEST.

val jwe = JsonWebEncryption()

jwe.payload = decryptedText
jwe.algorithmHeaderValue = KeyManagementAlgorithmIdentifiers.RSA1_5
jwe.encryptionMethodHeaderParameter = ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512
jwe.key = stringToRSAPublicKey(publicKey)
val serializedJwe = jwe.compactSerialization

The public key string is the following

"MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBGvNkLnetAtR+QSttxIkQ9" +
"mH7pbbjl2UqRu5UDO9kuEiYh4b70JxPN8v1exkuW/FLmxKjdRVq7gNWstumIGm1W" +
"8cf4RtFj88pvZUaVg6NZ21iLAIHtnhb2D/4eBOI8HXdhdZ+bEd+BJbu1rlqm0Rs1" +
"1jzYukR35/n44me3fbP9DH3JmSM8s0F8RmlIY0VqDnSOCOazNupVtJQFWeDIyfcV" +
"/coW+RRrFq5KNwnHPxdl5o3PR3OZgV27H/eBuKxIEGvjBUYchSjAAdJYAnfISvcd" +
"huLeYocZGi5WHEswrQBoUG8GflcdMJTvtTL5PtJG2WdcurIQA6iD2fSdBgQpARJF" +
 "AgMBAAE=

In a nutshell, I need to convert this taken from iOS code into android equivalent code:

enter image description here enter image description here

msamhoury
  • 333
  • 3
  • 12

1 Answers1

0

You should use X509EncodedKeySpec to convert String to Public Key. Here is the code.

val keySpecPublic = X509EncodedKeySpec(Base64.decode(publicKeyString, Base64.DEFAULT))
val publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpecPublic) as RSAPublicKey

Hope it will work.

Ensar Bayhan
  • 864
  • 10
  • 14