【问题标题】:Use SSH private key as an RSA private key for decrypting data encrypted with public key使用 SSH 私钥作为 RSA 私钥来解密用公钥加密的数据
【发布时间】:2020-11-04 12:31:31
【问题描述】:

我正在尝试使用系统的 SSH Pub 和私钥来加密和解密 Go 中的数据(字符串等)。

我已经能够使用 SSH 公钥作为 RSA 公钥成功加密数据。但是,在尝试使用 SSH 私钥(尝试将其用作 RSA 私钥)解密相同数据时,我无法使用相同/相似的方法

加密代码 - 有效

func EncryptWithPublicKey(pubKeyLoc string, symCipherText bytes.Buffer) ([]byte, error) {
//read file first
pub, err := ioutil.ReadFile(pubKeyLoc)
if err != nil {
    return nil, err
}

parsed, _, _, _, err := ssh.ParseAuthorizedKey(pub)
if err != nil {
    return nil, err
}

parsedCryptoKey := parsed.(ssh.CryptoPublicKey)
pubCrypto := parsedCryptoKey.CryptoPublicKey()
rsaPub := pubCrypto.(*rsa.PublicKey)

encryptedBytes, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, rsaPub, symCipherText.Bytes(), nil)
if err != nil {
    return nil, err
}

return encryptedBytes, nil

解密代码 - 不起作用!

func DecryptWithPrivateKey(privPath string, wrappedData []byte) ([]byte, error) {
priv, err := ioutil.ReadFile(privPath)
if err != nil {
    return nil, err
}

block, _ := pem.Decode(priv)
der, err := x509.DecryptPEMBlock(block, []byte(""))
if err != nil {
    return nil, err
}

privKey, err := x509.ParsePKCS1PrivateKey(der)

// dec, err := ssh.ParseRawPrivateKey(priv)
// if err != nil {
//  return nil, err
// }

// parsedKey := dec.(*rsa.PrivateKey)

decryptBytes, err := privKey.Decrypt(nil, wrappedData, &rsa.OAEPOptions{Hash: crypto.SHA256})
if err != nil {
    return nil, err
}

return decryptBytes, nil

不知道我在这里做错了什么。

更新 - 在下面回答

在找到解决方案之前,我遇到了两个错误

  • 解密错误或
  • 在标头错误中发现非 DEK 信息

它们已在解决方案中得到解决

【问题讨论】:

  • 一般来说,说某事不工作并不是特别有用。你怎么知道它不起作用?您是否收到一些错误消息?你得到不正确的答案吗?您提供的详细信息越多,您获得好的答案的可能性就越大。
  • “SSH 密钥”不是一种密钥。您的 SSH 密钥(这些天)很可能是 RSA 密钥,因此使用它“作为”RSA 密钥只是在使用它 - 更准确地说,您有一个 RSA 密钥,而您恰好将它用于 SSH。但就 Polk 而言,我们需要知道您遇到的具体问题是“不工作”之外的问题。
  • 是的,我知道 SSH 密钥是 RSA 密钥。但在这种情况下,我使用它来区分在 Go 中将其用作 RSA 密钥。当我尝试解密加密的有效负载并且解析 pem 并将其用作 PKCS1 密钥时,我得到的错误是一个解密错误,我得到一个“No DEK-info header in block”

标签: go encryption ssh cryptography rsa


【解决方案1】:

我找到了解决这个问题的方法。

事实证明,我做错了一些事情。

  1. 我在尝试解密时没有考虑 base64 编码 (d'uh)
  2. 但更重要的是,我没有正确解析我试图用来解密加密负载的私钥。

代码如下:

func DecryptWithPrivateKey(privPath string, wrappedData []byte) ([]byte, error) {
//read private key
priv, err := ioutil.ReadFile(privPath)
if err != nil {
    return nil, err
}

privKey, err := ssh.ParseRawPrivateKey(priv)

if err != nil {
    return nil, err
}

//get raw encrypted payload
data, err := base64.StdEncoding.DecodeString(string(wrappedData))
if err != nil {
    return nil, err
}

//parse the OpenSSH key as an RSA Private Key
parsedKey := privKey.(*rsa.PrivateKey)
decryptBytes, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, parsedKey, data, nil)

if err != nil {
    return nil, err
}

return decryptBytes, nil
}

【讨论】:

    最近更新 更多