1 year ago
#383144
Adrian Le Roy Devezin
Translating python RSA and Cipher_PKCS1_v1_5 code to java/kotlin
I have some small python code that I want to translate into the equivalent Java/Kotlin code. The python code gets a key off a JSON and encodes it to utf-8 standard. It then base64 decodes it and seems to import an RSA key. I am unsure what the cipher part is doing. However it then encrypts the email, password, and phone with the cipher, and then base64 encodes it. I have attempted to do it myself but get lost at the point of the cipher.
Python
jsonValue = resp.json()["Content"]["pkey"].encode()
pkeyBase64 = base64.b64decode(jsonValue).decode()
pkey = RSA.importKey(pkeyBase64)
cipher = Cipher_PKCS1_v1_5.new(pkey)
email = base64.b64encode(cipher.encrypt(email.encode())).decode()
phone = base64.b64encode(cipher.encrypt(phone.encode())).decode()
password = base64.b64encode(cipher.encrypt(password.encode())).decode()
Attempt In Kotlin
val base64Decoder = Base64.getDecoder()
val base64Encoder = Base64.getEncoder()
val base64EncodedPkey = body["Content"]?.jsonObject?.get("pkey")?.toString()
val base64DecodedPkey = base64Decoder.decode(base64EncodedPkey)
val pkey = getPrivateKey(String(base64DecodedPkey)) ?: return
val cipher = Cipher.getInstance("RSA")
private fun getPrivateKey(base64PrivateKey: String): PrivateKey? {
var privateKey: PrivateKey? = null
val keySpec = PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.toByteArray()))
var keyFactory: KeyFactory? = null
try {
keyFactory = KeyFactory.getInstance("RSA")
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
}
try {
privateKey = keyFactory?.generatePrivate(keySpec)
} catch (e: InvalidKeySpecException) {
e.printStackTrace()
}
return privateKey
}
python
java
kotlin
encryption
rsa
0 Answers
Your Answer