You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js RSA公钥加密Android端SecretKey并在服务端解密

RSA公钥加密Android端SecretKey并在Node.js端解密实现

需求概述

通过Node.js服务器生成RSA密钥对,使用公钥加密Android客户端创建的SecretKey,最终在Node.js服务器完成解密操作。

Node.js密钥对生成代码

async generateKeyPair(userId: string): Promise<string> {
    const { publicKey, privateKey } = generateKeyPairSync(
      'rsa',
      {
        modulusLength: 2048,
        publicKeyEncoding: {
          type: 'spki', // 与Java的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}`
  }

Android客户端加密代码

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-----
", "")
            .replace("
", "")
            .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)
    }

Node.js服务端解密代码

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
    }

内容的提问来源于stack exchange,提问作者Harsh Vardhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:22:46