简体   繁体   English

RSA-如何检查公钥信息?

[英]RSA - How to check for public key info?

I encrypt and decrypt data using the RSACryptoServiceProvider in C#, and when I generate a new keypair, I return the private key to the caller of the method and then save the public key to a homemade PKI (just a dictionary with the keyBlob and a unique identifier). 我使用C#中的RSACryptoServiceProvider加密和解密数据,并在生成新的密钥对时,将私钥返回给方法的调用者,然后将公钥保存到自制的PKI(仅包含keyBlob和唯一的字典)标识符)。

My problem is this: since I need to store the public key, I don't want to accidentally store a private key in the PKI. 我的问题是:由于我需要存储公钥,因此我不想在PKI中意外存储私钥。 However, since I also need to actually write the private key to a file, I am working with byte arrays exported with the ExportCspBlob method. 但是,由于我实际上还需要将私钥写入文件,因此我正在处理通过ExportCspBlob方法导出的字节数组。

My question: 我的问题:
How do I ensure, by checking the byte[] that I parse into my StoreKey method, that it is in fact a public key and it does not contain private key information? 如何通过检查解析到StoreKey方法中的byte[]来确保它实际上是公钥,并且不包含私钥信息?

For clarification, here is the relevant code: 为了澄清起见,以下是相关代码:

public static bool StoreKey(byte[] publicKeyParameters, string uniqueIdentifier)
{
    bool success = false;
    if (!keyCollection.ContainsKey(uniqueIdentifier))
    {
        if (!keyCollection.ContainsValue(publicKeyParameters))
        {
            keyCollection.Add(uniqueIdentifier, publicKeyParameters);
            success = true;
        }
    }
    return success;
}

And the GenerateKeys method: GenerateKeys方法:

public static byte[] GenerateKeys(string uniqueIdentifier)
{
    byte[] privateKeyBlob;

    using (var rsa = new RSACryptoServiceProvider(4096))
    {
        try
        {
            byte[] publicKey = rsa.ExportCspBlob(false);

            privateKeyBlob = rsa.ExportCspBlob(true);

            PublicKeyInfrastructure.StoreKey(publicKey, uniqueIdentifier);
        }
        finally
        {
            //// Clear the RSA key container, deleting generated keys.
            rsa.PersistKeyInCsp = false;
        }
    }
    return privateKeyBlob;
}

Since I am working on two different classes, I would like to abstain from initializing a RSACryptoServiceProvider in my PKI, just to import the key and check for it. 由于我正在研究两个不同的类,因此我不想在我的PKI中初始化RSACryptoServiceProvider ,仅导入密钥并进行检查。 Is this possible? 这可能吗?

According to MSDN, the output of ExportCspBlob is compatible with CAPI, and according to the documentation for the CAPI BLOBHEADER , the first byte represents the key type. 根据MSDN, ExportCspBlob的输出与CAPI兼容,并且根据CAPI BLOBHEADER的文档,第一个字节代表密钥类型。 Specifically, if the first byte is 0x07, it's a private key, whereas 0x06 is a public key. 具体来说,如果第一个字节为0x07,则为私钥,而0x06为公钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM