使用x509证书签署json文档或字符串 [英] Signing a json document or string with x509 certificate
问题描述
如何使用x509证书签署json文档或字符串?
How to signing a json document or string with x509 certificate?
public static void fund()
{
string filePath = @"C:\Users\VIKAS\Desktop\Data.xml";
//Read the file
XmlDocument xmlDoc = new XmlDocument();
XElement ele = XElement.Load(filePath);
String Xml = ele.ToString();
xmlDoc.LoadXml(Xml);
string signature = SignedXMLCert(xmlDoc);
bool verified = ValidateSignature(signature);
}
public static string SignedXMLCert(XmlDocument xmlDoc)
{
string startupPath = AppDomain.CurrentDomain.BaseDirectory + @"Certificates\unidesk.p12";
// startupPath = AppDomain.CurrentDomain.BaseDirectory + @"\Certificates\BBPS_enc.cer";
//X509Certificate2 cert = new X509Certificate2(@"D:\Sonal\AXISOU_TEST.P12", "axisbank", X509KeyStorageFlags.Exportable);
X509Certificate2 cert = new X509Certificate2(startupPath, "axisbank", X509KeyStorageFlags.Exportable);
// string PrivateKey = GetRSAPrivateKeyBase64(cert);
var privateKey = cert.PrivateKey as RSACryptoServiceProvider;
SignedXml signedXml = new SignedXml(xmlDoc);
signedXml.SigningKey = privateKey;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
KeyInfo keyInfo = new KeyInfo();
//startupPath = AppDomain.CurrentDomain.BaseDirectory + @"\Certificates\BBPS_enc.cer";
X509Certificate MSCert = new X509Certificate(startupPath, "axisbank", X509KeyStorageFlags.Exportable);
// X509Certificate MSCert = X509Certificate.CreateFromCertFile(startupPath);
keyInfo.AddClause(new KeyInfoX509Data(MSCert));
signedXml.KeyInfo = keyInfo;
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
return xmlDoc.InnerXml.ToString();
}
public static bool ValidateSignature(String signedServiceMetadataContent)
{
bool result = false;
X509Certificate2 cert = GetCertificate();
//Load the key
CspParameters csp = new CspParameters();
csp.KeyContainerName = cert.PublicKey.Key.ToString();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
//Load XML document
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
xmlDocument.LoadXml(signedServiceMetadataContent);
//create a SignedXml and load the xml document
SignedXml signedXml = new SignedXml(xmlDocument);
//find signature and create signature node list
XmlNodeList xmlNodeList = xmlDocument.GetElementsByTagName("Signature");
if (xmlNodeList.Count <= 0)
{
throw new CryptographicException("Verification failed: No Signature was found in the document.");
}
// if more than one signature was found.
if (xmlNodeList.Count >= 2)
{
throw new CryptographicException("Verification failed: More that one signature was found for the document.");
}
//Load signature into SignedXml
signedXml.LoadXml((XmlElement)xmlNodeList[0]);
//check the signature
result = signedXml.CheckSignature(cert, true);
//result = signedXml.CheckSignature(rsa);
return result;
}
private static X509Certificate2 GetCertificate()
{
string startupPath = AppDomain.CurrentDomain.BaseDirectory + @"Certificates\unidesk.p12";
X509Certificate2 cert = new X509Certificate2(startupPath, "axisbank", X509KeyStorageFlags.Exportable);
return new X509Certificate2(cert);
}
推荐答案
XMLDsig签名格式仅适用于XML文档.您可以应用为JSON文档设计的 JSON Web签名(JWS).
XMLDsig signature format is only suitable for XML documents. You could apply JSON Web Signature (JWS) which is designed for JSON documents.
具有紧凑序列化的JWS表示为(请参见 RFC7515 )
A JWS with compact serialization is represented by (see RFC7515)
BASE64URL(UTF8(JWS Protected Header)) || '.' ||
BASE64URL(JWS Payload) || '.' ||
BASE64URL(JWS Signature)
JWS受保护的标头
最简单的标头由alg
组成. RS256
表示具有SHA-256的算法RSA
The simplest header is composed by alg
. RS256
means algorithm RSA with SHA-256
{"alg":"RS256"}
您可以添加其他参数,例如x5c
(X.509证书链)或cty
(内容类型)
You can add other parameters such as x5c
(X.509 Certificate Chain) or cty
(Content Type)
JWS有效负载
有效负载是您的JSON对象,编码为base64url
The payload is your JSON object encoded as base64url
eyJ1cGRhdGVTUlJlcSI6IHsgImluY2lkZW50SUQiOiAiIiwgImNyZWF0ZWRCeSI6ICIwMzcwMjIwMDAwNDIwNDgiLCAiZGVzY3JpcHRpb24iOiAiMDM3MDIyMDAwMDQyMDQ4IiwgImlzVmlzaWJsZVRvQ3VzdG9tZXIiOiAiMyIsICJ1cGRhdGVUeXBlIjogIjIiLCAiYWN0aXZpdHlUeXBlIjogIjIiLCAiY3JlYXRlZE9uIjogIjIwMTYtMDktMDggMTc6NTciLCAibGFzdFVwZGF0ZSI6ICIyMDE2LTA5LTA4IDE3OjU3IiwgInN0YXR1cyI6ICIyIiwgImNsb3NlZFRpbWUiOiAiIiB9LCAic3ViSGVhZGVyIjogeyAidmFsdWUiOiB7ICJyZXF1ZXN0VVVJRCI6ICIxMjMiLCAiU2VydmljZVJlcXVlc3RJZCI6ICJBRS5NQVBTLlVESy5TU1RQIiwgIlNlcnZpY2VSZXF1ZXN0VmVyc2lvbiI6ICIxLjAiLCAiQ2hhbm5lbElkIjogIk1BUFMifX19
JWS签名
JWS签名的计算依据
The JWS signature is computed on
BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload))
构建以下字符串,并使用证书的私钥应用RSA数字签名算法
Build the following string and apply the RSA digital signature algorithm with the private key of your certificate
eyJhbGciOiJSUzI1NiJ9.eyJ1cGRhdGVTUlJlcSI6IHsgImluY2lkZW50SUQiOiAiIiwgImNyZWF0ZWRCeSI6ICIwMzcwMjIwMDAwNDIwNDgiLCAiZGVzY3JpcHRpb24iOiAiMDM3MDIyMDAwMDQyMDQ4IiwgImlzVmlzaWJsZVRvQ3VzdG9tZXIiOiAiMyIsICJ1cGRhdGVUeXBlIjogIjIiLCAiYWN0aXZpdHlUeXBlIjogIjIiLCAiY3JlYXRlZE9uIjogIjIwMTYtMDktMDggMTc6NTciLCAibGFzdFVwZGF0ZSI6ICIyMDE2LTA5LTA4IDE3OjU3IiwgInN0YXR1cyI6ICIyIiwgImNsb3NlZFRpbWUiOiAiIiB9LCAic3ViSGVhZGVyIjogeyAidmFsdWUiOiB7ICJyZXF1ZXN0VVVJRCI6ICIxMjMiLCAiU2VydmljZVJlcXVlc3RJZCI6ICJBRS5NQVBTLlVESy5TU1RQIiwgIlNlcnZpY2VSZXF1ZXN0VmVyc2lvbiI6ICIxLjAiLCAiQ2hhbm5lbElkIjogIk1BUFMifX19
最后将签名编码为base64url并将结果附加到以前的数据中以进行签名.您将获得一个像这样的JWS hhhhh.ppppp.sssss
,其中hhhhh
是标头ppppp
有效负载,而sssss
是签名
Finally encode the signature as base64url and append the result to the previous data to sign. You will get a JWS like this hhhhh.ppppp.sssss
where hhhhh
is the header ppppp
the payload and sssss
the signature
使用以下链接到
- Base64url编码:解码代码/编码修改后的base64 URL
- 使用.net和证书(C#)签名并验证签名: https://blogs.msdn.microsoft.com/alejacma/2008/06 /25/如何使用网络和证书C/ 签名和验证签名
- Base64url encoding: Code for decoding/encoding a modified base64 URL
- Sign and verify signature with .net and a certificate (C#) : https://blogs.msdn.microsoft.com/alejacma/2008/06/25/how-to-sign-and-verify-the-signature-with-net-and-a-certificate-c/
要从紧凑格式hhhhh.ppppp.sssss
验证签名,请base64url对签名sssss
进行解码,并使用签名数据hhhhh.ppppp
和使用的证书来验证签名
To verify a signature from the compact format hhhhh.ppppp.sssss
, base64url decode the signature sssss
, and verify the signature with the signed data hhhhh.ppppp
and the used certificate
这篇关于使用x509证书签署json文档或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!