Reputation: 1
I am trying to encrypt secretKey created on android client with the publicKey(RSA) generated on nodeJs server and decrypt that secretKey on nodeJs server.
This is the Android Client Side Code .
override suspend fun encryptClientKey(publicKeyString: String): String {
println("Inside encryptClientKey fun publicKeyString as Base64 : $publicKeyString")
val publicKeyDecodedBuffer = Base64.decode(publicKeyString, Base64.DEFAULT)
println("Inside encryptClientKey fun publicKeyDecoded as Buffer
:$publicKeyDecodedBuffer")
var pemFile = String(publicKeyDecodedBuffer)
println("Inside encryptClientKey fun pemFile as String: $pemFile")
pemFile = pemFile
.replace("-----BEGIN PUBLIC KEY-----\n", "")
.replace("\n", "")
.replace("-----END PUBLIC KEY-----", "")
println("Inside encryptClientKey() pemFile as String: $pemFile")
val decodedKeyMaterialInsidePemFile = Base64.decode(pemFile, Base64.DEFAULT)
println("Inside encryptClientKey fun decodedPemFile of servers publicKey as Buffer: ${String(decodedKeyMaterialInsidePemFile)}")
val publicKeySpec = X509EncodedKeySpec(decodedKeyMaterialInsidePemFile)
val keyFactory = KeyFactory.getInstance("RSA")
val publicKey = keyFactory.generatePublic(publicKeySpec)
val cipherForClientKeyEncryption = Cipher.getInstance("RSA/ECB/PKCS1Padding")
cipherForClientKeyEncryption.init(Cipher.ENCRYPT_MODE, publicKey)
val decryptedSecretKeyInBase64 = decryptOpener(encryptedOpener = getEncryptedOpenerKey())
println("Inside encryptClientKey() decryptedSecretKeyInBase64: $decryptedSecretKeyInBase64")
val decipheredSKeyInBuffer = Base64.decode(decryptedSecretKeyInBase64, Base64.DEFAULT)
return Base64.encodeToString(cipherForClientKeyEncryption.doFinal(decipheredSKeyInBuffer), Base64.DEFAULT)
}
This is the NodeJs Server Side
async decryptClientKey(secretKey: string, privateKey: string, userId: string): Promise<Buffer> {
console.log(Buffer.from(privateKey, 'base64').toString())
const keyInPemFormat = Buffer.from(privateKey, 'base64').toString()
const sKeyBufferFromB64 = Buffer.from(secretKey, 'base64')
const sKeyHexForm = sKeyBufferFromB64.toString('hex')
const privateKeyObject = createPrivateKey({
key: keyInPemFormat,
format: 'pem',
passphrase: userId
})
const sKey = privateDecrypt(
{
key: privateKeyObject,
padding: constants.RSA_PKCS1_PADDING,
},
Buffer.from(sKeyHexForm, 'hex')
)
return sKey
}
This is how I generated Pair in NodeJs
async generateKeyPair(userId: string): Promise<string> {
const { publicKey, privateKey } = generateKeyPairSync(
'rsa',
{
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki', // same as what Java calls X509Encoded
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: userId,
},
}
)
const privateKeyBase64Form = (Buffer.from(privateKey)).toString('base64')
const publicKeyBase64Form = (Buffer.from(publicKey)).toString('base64')
return `${publicKeyBase64Form}%${privateKeyBase64Form}`
}
Upvotes: 0
Views: 60