使用SHA1RSA和现有rsa私钥C#签署字符串

时间:2018-11-18 05:27:35

标签: c# android cryptography rsa sign

我有一个RSA私钥,我想用它签名数据。我写了这段代码,但是没用:

public string Sign(string text)
{
    var sha = new SHA1Managed();
    var encoding = new UTF8Encoding();
    var bytes = encoding.GetBytes(text);
    var digest = sha.ComputeHash(bytes);

    var cert = new X509Certificate2(Convert.FromBase64String(PermissionKey));
    var rsa = (RSACryptoServiceProvider)cert.PrivateKey;
    var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
    rsaFormatter.SetHashAlgorithm("SHA1");

    var SignedHashValue = rsa.SignData(digest, sha);
    return Convert.ToBase64String(SignedHashValue).Replace("=", "") + "\n";
}

我得到这个例外:

'Cannot find the requested object. 

当我尝试创建X509Certificate2时:

var cert = new X509Certificate2(Convert.FromBase64String(PermissionKey));

PS: 我很累,用c#模拟android代码。这是主要的android:

public static PrivateKey makePrivateKeyFromPermissionKey(String permissionKey)
        throws InvalidKeySpecException, NoSuchProviderException, NoSuchAlgorithmException {
    KeyFactory keyFactory;
    byte[] certificate = decode(
            permissionKey
                    .replaceAll("\\n", "")
                    .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                    .replace("-----END RSA PRIVATE KEY-----", "")
    );
    if (Build.VERSION.SDK_INT < 27) {
        keyFactory = KeyFactory.getInstance("RSA", "BC");
    } else {
        keyFactory = KeyFactory.getInstance("RSA");
    }
    return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(certificate));
}

1 个答案:

答案 0 :(得分:0)

我找到了答案。我使用CSharp_easy_RSA_PEM库来读取私钥。

public static string Sign(string text)
{
    var privateRSAkey = Crypto.DecodeRsaPrivateKey(PermissionKey);
    var rsa = privateRSAkey;

    var hasher = new SHA1CryptoServiceProvider();
    var e = new UTF8Encoding(true);
    var bytesFirmados = rsa.SignData(e.GetBytes(text), hasher);

    return Convert.ToBase64String(bytesFirmados);
}