使用 RSA-2048 server-public-key 加密 client-private-key

Encrypt client-private-key with RSA-2048 server-public-key

我需要使用 RSA-2048 server-public-key 加密 client-private-key。 我知道私钥显然比 public 密钥长,我不确定是否可能...但是我看到在 Python 中完成了类似的任务,所以我想知道你的意见.

/* main */

clientPrivateKey, _ := generateRsaPair(2048)
_, serverPublicKey := generateRsaPair(2048)

clientPrivateKeyAsByte := privateKeyToBytes(clientPrivateKey)

encryptWithPublicKey(clientPrivateKeyAsByte, serverPublicKey) 

致命错误 crypto/rsa:消息对于 RSA public 密钥大小来说太长

/* Functions */

func generateRsaPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey) {
    privkey, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
        log.Error(err)
    }
    return privkey, &privkey.PublicKey
}

func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte {
    hash := sha512.New()
    ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil)
    checkError(err)

    return ciphertext
}

func privateKeyToBytes(priv *rsa.PrivateKey) []byte {
    privBytes := pem.EncodeToMemory(
        &pem.Block{
            Type:  "RSA PRIVATE KEY",
            Bytes: x509.MarshalPKCS1PrivateKey(priv),
        },
    )

    return privBytes
}

如果您想加密大于密钥大小的内容,那么您可以简单地使用混合加密。您首先使用随机 AES 密钥加密(或包装,如果特定的包装操作可用)私钥的编码,例如使用 AES-CBC 或 AES-CTR (IV 全部为零)。然后使用私钥加密该 AES 密钥。密文由加密的 AES 密钥和加密的数据组成 - 在本例中为 RSA 私钥。

但是请注意,私钥实际上应该由一个实体管理。它不是无缘无故称为 private 密钥。分发私钥通常被认为是糟糕的密钥管理做法。