How do I decode a BASE64, PCKS-8 representation of a private key in .net?

╄→гoц情女王★ 提交于 2020-01-11 09:44:21

问题


I'm working on integrating my application with the Walmart Marketplace API. Their documentation pretty much says if you don't use Java you're on your own. My application uses VB.Net but I'm open to implementing this in any .net language.

From their instructions:

Sign the byte array representation of this data by:

Decoding the Base 64, PKCS-8 representation of your private key. Note that the key is encoded using PKCS-8. Libraries in various languages offer the ability to specify that the key is in this format and not in other conflicting formats such as PKCS-1. Use this byte representation of your key to sign the data using SHA-256 With RSA. Encode the resulting signature using Base 64.

At this point I'm stuck at the first part. I cannot figure out how to decode the private key in .net. Once I figure this out, I'll get to the second part of signing the request.

My question is if there is any code snippet or library out there that can help me with this. Some sample code for using any library would also be appreciated.


回答1:


it works for me using c# .net 4.6

using System;
using System.Security.Cryptography;
public static string SignData(string stringToBeSigned, string encodedPrivateKey)
        {
            string signedData = string.Empty;
            try
            {
                var decodeKey = Convert.FromBase64String(privateEncodedStr);
                var key = CngKey.Import(decodeKey, CngKeyBlobFormat.Pkcs8PrivateBlob);
                var alg = new RSACng(key);
                byte[] data = Encoding.UTF8.GetBytes(stringToBeSigned);
                byte[] signData = alg.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                signedData = Convert.ToBase64String(signData);
            }
            catch (Exception)
            {
                throw;
            }
            return signedData;
        }


来源:https://stackoverflow.com/questions/37531044/how-do-i-decode-a-base64-pcks-8-representation-of-a-private-key-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!