public void Test() { //var keys = GenerateKeys(1024); //Console.WriteLine(DotNetUtilities.ToRSA(((RsaPrivateCrtKeyParameters)keys.Private)).ToXmlString(true)); //Console.WriteLine(); //Console.WriteLine(DotNetUtilities.ToRSA(((RsaPrivateCrtKeyParameters)keys.Private)).ToXmlString(false)); var keys = GetRsaKeyPair(); byte[] msg = Guid.NewGuid().ToByteArray(); ISigner eng = new RsaDigestSigner(new Sha256Digest()); eng.Init(true, keys.Private); eng.BlockUpdate(msg, 0, msg.Length); byte[] s = eng.GenerateSignature(); eng = new RsaDigestSigner(new Sha256Digest()); eng.Init(false, keys.Public); eng.BlockUpdate(msg, 0, msg.Length); Assert.IsTrue(eng.VerifySignature(s)); }
public void TestRsaDigestSigner() { BigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); BigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); BigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); BigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); BigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); BigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); BigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); byte[] msg = new byte[] { 1, 6, 3, 32, 7, 43, 2, 5, 7, 78, 4, 23 }; RsaDigestSigner signer = new RsaDigestSigner(new Sha1Digest()); signer.Init(true, rsaPrivate); signer.BlockUpdate(msg, 0, msg.Length); byte[] sig = signer.GenerateSignature(); signer.Init(false, rsaPublic); signer.BlockUpdate(msg, 0, msg.Length); Assert.IsTrue(signer.VerifySignature(sig), "RSA IDigest Signer failed."); }
public byte[] GenerateSignature(byte[] data, string privateKey) { var signer = new RsaDigestSigner(new Sha256Digest()); signer.Init(true, GetPrivateKeyParameters(privateKey)); signer.BlockUpdate(data, 0, data.Length); return(signer.GenerateSignature()); }
public byte[] SignMessage(byte[] message) { var signer = new RsaDigestSigner(new Sha512Digest()); signer.Init(true, KeyPair.Private); signer.BlockUpdate(message, 0, message.Length); return(signer.GenerateSignature()); }
private byte[] SignRsa(IDigest digest, byte[] buffer, int length) { RsaDigestSigner signer = new RsaDigestSigner(digest); signer.Init(true, new ParametersWithRandom(PrivateKeyFactory.CreateKey(PrivateKey), _secureRandom)); signer.BlockUpdate(buffer, 0, length); return(signer.GenerateSignature()); }
/// <summary> /// Signs the passed in data with a private key /// </summary> /// <param name="privateKey">the private key used to create the signature</param> /// <param name="data">The data to sign</param> /// <returns>the signature as a byte array</returns> public byte[] Sign(byte[] privateKey, byte[] data) { var signer = new RsaDigestSigner(new Sha1Digest()); var privKey = (RsaKeyParameters)CreateAsymmetricKeyParameterFromPrivateKeyInfo(privateKey); signer.Init(true, privKey); signer.BlockUpdate(data, 0, data.Length); return(signer.GenerateSignature()); }
public byte[] SignMessageAsBytes(string message, string privateKey) { var bytesToEncrypt = Encoding.UTF8.GetBytes(message); var signer = new RsaDigestSigner(GetShaDigest()); signer.Init(true, GetPrivate(privateKey)); signer.BlockUpdate(bytesToEncrypt, 0, bytesToEncrypt.Length); return(signer.GenerateSignature()); }
public static string SignContent(AsymmetricKeyParameter privateKey, string content) { var rsaDigestSigner = new RsaDigestSigner(new Sha1Digest()); rsaDigestSigner.Init(true, privateKey); var bytes = Encoding.UTF8.GetBytes(content); rsaDigestSigner.BlockUpdate(bytes, 0, bytes.Length); return(Convert.ToBase64String(rsaDigestSigner.GenerateSignature())); }
private static byte[] GetSignature(MetaInfCertSfBuilder signature, ICipherParameters privateKey) { var signer = new RsaDigestSigner(new Sha1Digest()); //var signer = new RSADigestSigner(new MD5Digest()); signer.Init(true, privateKey); var raw = signature.ToArray(); signer.BlockUpdate(raw, 0, raw.Length); return(signer.GenerateSignature()); }
public string GenerateSignature(string privateKey, string password, string documentId) { var keyPair = ReadPrivateKey(privateKey, password); var sha1Digest = new Sha1Digest(); var rsaDigestSigner = new RsaDigestSigner(sha1Digest); rsaDigestSigner.Init(true, keyPair); var documentIdToSign = Encoding.ASCII.GetBytes(documentId); rsaDigestSigner.BlockUpdate(documentIdToSign, 0, documentIdToSign.Length); return(Convert.ToBase64String(rsaDigestSigner.GenerateSignature())); }
/// <summary> /// Creates an instance of a 'SoftToken'. /// </summary> /// <param name="name">The token's name.</param> /// <param name="certPath">Path to OCSP signer certificate.</param> /// <param name="keyPath">Path to OCSP signer certificate key.</param> public override byte[] SignData(byte[] data, IDigest digestAlgorithm) { byte[] signature; RsaDigestSigner rsaSigner = new RsaDigestSigner(digestAlgorithm); rsaSigner.Init(true, _privateKey); rsaSigner.BlockUpdate(data, 0, data.Length); signature = rsaSigner.GenerateSignature(); rsaSigner.Reset(); return(signature); }
public static byte[] Sign(byte[] data) { //RSAParameters p = new RSAParameters(); //var publicKey = DotNetUtilities.GetRsaPublicKey(p); //var cs = new RSACryptoServiceProvider(1024); //var publicKey = DotNetUtilities.GetRsaPublicKey(cs); var publicKey = GetRsaKeyPair(); ISigner eng = new RsaDigestSigner(new Sha256Digest()); //new PssSigner(new RsaEngine(), digest); eng.Init(true, publicKey.Private); eng.BlockUpdate(data, 0, data.Length); return(eng.GenerateSignature()); }
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hashAlgorithm != HashAlgorithmName.SHA256) { throw new ArgumentException( $"Unsupported HashAlgorithmName '{hashAlgorithm}', only SHA256 supported.", nameof(hashAlgorithm)); } if (padding != RSASignaturePadding.Pkcs1) { throw new ArgumentException( $"Unsupported RSASignaturePadding '{padding}', only Pkcs1 supported.", nameof(padding)); } var signer = new RsaDigestSigner(new NullDigest(), NistObjectIdentifiers.IdSha256); signer.Init(true, _parameters); signer.BlockUpdate(hash, 0, hash.Length); return(signer.GenerateSignature()); }
/* * SIGNING IMPLEMENTATION */ private void sign(RestRequest request) { byte[] bodyBytes = request.Body(); var sha256 = new Sha256Digest(); var signer = new RsaDigestSigner(sha256); signer.Init(true, (ICipherParameters)rsaKeyPair.Private); signer.BlockUpdate(bodyBytes, 0, bodyBytes.Length); byte[] signature = signer.GenerateSignature(); string hexEncoded = Hex.ToHexString(signature); var header = string.Format("{0} RS256-hex {1}", signingAPIKey, hexEncoded); request.AddHeader("Signature", header); }
public static string GetSignature(string message) { byte[] messageBytes = message.ToByteArray(); RsaDigestSigner signer = new RsaDigestSigner(new Sha256Digest()); signer.Init(true, TransformKey(KeyType.PrivateKey)); signer.BlockUpdate(messageBytes, 0, messageBytes.Length); try { byte[] signature = signer.GenerateSignature(); return(signature.ToBase64()); } catch (Exception e) { FileHelper.WriteFile(ErrorHelper.FormatError(e), FileHelper.ErrorPath, true); return(null); } }
public void Sign(string privateKey) { string canonicalHeader = String.Format( "Method:{0}\nHashed Path:{1}\nX-Ops-Content-Hash:{4}\nX-Ops-Timestamp:{3}\nX-Ops-UserId:{2}", method, requestUri.AbsolutePath.ToBase64EncodedSha1String(), client, timestamp, body.ToBase64EncodedSha1String()); byte[] input = Encoding.UTF8.GetBytes(canonicalHeader); var pemReader = new PemReader(new StringReader(privateKey)); AsymmetricKeyParameter key = ((AsymmetricCipherKeyPair)pemReader.ReadObject()).Private; ISigner signer = new RsaDigestSigner(new NullDigest()); signer.Init(true, key); signer.BlockUpdate(input, 0, input.Length); signature = Convert.ToBase64String(signer.GenerateSignature()); }
public void SignMessage(string privateKey) { string canonicalHeader = String.Format( "Method:{0}\nHashed Path:{1}\nX-Ops-Content-Hash:{4}\nX-Ops-Timestamp:{3}\nX-Ops-UserId:{2}", _httpMethod, _chefUri.AbsolutePath.ToBase64EncodedSha1String(), _chefClient, _timestamp, _body.ToBase64EncodedSha1String()); byte[] input = Encoding.UTF8.GetBytes(canonicalHeader); TextReader pemStream; if (privateKey.Contains("UNSET") && ChefConfig.ValidationKey != "UNSET") { ChefConfig.ValidationKey = ChefConfig.ValidationKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "-----BEGIN RSA PRIVATE KEY-----\n"); ChefConfig.ValidationKey = ChefConfig.ValidationKey.Replace("-----END RSA PRIVATE KEY-----", "\n-----END RSA PRIVATE KEY-----"); pemStream = new StringReader(ChefConfig.ValidationKey); } else { pemStream = File.OpenText(privateKey); } var pemReader = new PemReader(pemStream); AsymmetricKeyParameter key = ((AsymmetricCipherKeyPair)pemReader.ReadObject()).Private; ISigner signer = new RsaDigestSigner(new NullDigest()); signer.Init(true, key); signer.BlockUpdate(input, 0, input.Length); _signature = Convert.ToBase64String(signer.GenerateSignature()); }
/// <summary> /// 利用私钥对内容进行加密 /// </summary> /// <param name="content">内容</param> /// <param name="key">私钥</param> /// <returns>加密后的内容</returns> public static string EncryptByPrivateKey(string content, string key) { if (string.IsNullOrEmpty(content)) { throw new ArgumentNullException(nameof(content)); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } var contentBytes = Encoding.UTF8.GetBytes(content); var keyBytes = Convert.FromBase64String(key); var keyParam = PrivateKeyFactory.CreateKey(keyBytes); var signer = new RsaDigestSigner(new Sha1Digest()); signer.Init(true, keyParam); signer.BlockUpdate(contentBytes, 0, contentBytes.Length); var resultBytes = signer.GenerateSignature(); return(Convert.ToBase64String(resultBytes)); }
internal override void Evaluate() { RsaDigestSigner signer = new RsaDigestSigner(provider.CreateEngine(EngineUsage.GENERAL), FipsShs.CreateDigest(FipsShs.Sha256)); signer.Init(false, new RsaKeyParameters(false, katM, katE)); signer.BlockUpdate(msg, 0, msg.Length); if (!signer.VerifySignature(FipsKats.Values[FipsKats.Vec.RsaStartupVerifySig])) { Fail("self test signature verify failed."); } signer.Init(true, new ParametersWithRandom(testPrivKey, Utils.testRandom)); signer.BlockUpdate(msg, 0, msg.Length); byte[] sig = signer.GenerateSignature(); if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.RsaStartupResultSig], sig)) { Fail("self test signature generate failed."); } }
private void NewMethod() { const string path = "/organizations/emc/cookbooks"; const string basePath = "https://chefsrv.foo800.local"; var timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); var method = "GET"; var clientName = "chefuser"; var hashedPath = ToBase64EncodedSha1String(path); var hashedBody = ToBase64EncodedSha1String(String.Empty); var canonicalHeader = String.Format("Method:{0}\nHashed Path:{1}\nX-Ops-Content-Hash:{2}\nX-Ops-Timestamp:{3}\nX-Ops-UserId:{4}", method, hashedPath, hashedBody, timestamp, clientName); string paths = @"C:\Custom File\paul3.pem"; byte[] input = Encoding.Default.GetBytes(canonicalHeader); StreamReader sr = new StreamReader(paths); PemReader pr = new PemReader(sr); AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject(); var key = KeyPair.Private; ISigner signer = new RsaDigestSigner(new NullDigest()); signer.Init(true, key); signer.BlockUpdate(input, 0, input.Length); signature = Convert.ToBase64String(signer.GenerateSignature()); var client = new HttpClient(); var message = new HttpRequestMessage(); message.Method = HttpMethod.Get; message.RequestUri = new Uri(basePath + path); message.Headers.Add("Accept", "application/json"); message.Headers.Add("X-Ops-Sign", "algorithm=sha1;version=1.0"); message.Headers.Add("X-Ops-UserId", clientName); message.Headers.Add("X-Ops-Timestamp", timestamp); message.Headers.Add("X-Ops-Content-Hash", hashedBody); message.Headers.Add("Host", "chefsrv.foo800.local:443"); message.Headers.Add("X-Chef-Version", "11.4.0"); //message.RequestUri = new Uri(basePath + path); //message.Headers.Add("Accept", "application/json"); //message.Headers.Add("Host", "chefsrv.foo800.local:443"); //message.Headers.Add("X-Chef-Version", "11.12.4"); //message.Headers.Add("X-Ops-Timestamp", timestamp); //message.Headers.Add("X-Ops-Sign", "algorithm=sha1;version=1.0"); //message.Headers.Add("X-Ops-Userid", clientName); //message.Headers.Add("X-Ops-Content-Hash", hashedBody); //message.Headers.Add("User-Agent", "Chef Knife/11.4.0 (ruby-1.9.2-p320; ohai-6.16.0; x86_64-darwin11.3.0; +http://opscode.com)"); var currentItem = new StringBuilder(); var i = 0; foreach (var line in signature.Split(60)) { message.Headers.Add(String.Format("X-Ops-Authorization-{0}", i++), line); } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback ( delegate { return(true); } ); var result = client.SendAsync(message).Result; var kk = result.StatusCode; var content = result.Content.ReadAsStringAsync(); }
public static void Main1(string[] args) { //公钥和密钥的生成,并加密解密测试 //RsaKeyGeneratorTest(); //done!!!!! byte[] msg = Encoding.UTF8.GetBytes("abcdefg"); string priKeyString = File.ReadAllText(@"E:\OwenProject\RSA\pc8_bc.pem"); string pubKeyString = File.ReadAllText(@"E:\OwenProject\RSA\pc8_bc_pub.pem"); using (TextReader priReader = new StringReader(priKeyString) , pubReader = new StringReader(pubKeyString)) { PemReader pemReader = new PemReader(priReader); var obj = pemReader.ReadObject(); var pri = obj as RsaPrivateCrtKeyParameters; //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //RSAParameters p = new RSAParameters(); //p.DP = pri.DP.ToByteArray(); //p.DQ = pri.DQ.ToByteArray(); //p.Exponent = pri.Exponent.ToByteArray(); //p.P = pri.P.ToByteArray(); //p.Q = pri.Q.ToByteArray(); //p.Modulus = pri.Modulus.ToByteArray(); //p.D = pri.PublicExponent.ToByteArray(); //p.InverseQ = pri.QInv.ToByteArray(); //rsa.ImportParameters(p); PemReader pemReaderPub = new PemReader(pubReader); var objPub = pemReaderPub.ReadObject(); var pub = objPub as RsaKeyParameters; //AsymmetricCipherKeyPair kp = new AsymmetricCipherKeyPair(pri, pub); RsaDigestSigner signer = new RsaDigestSigner(new Sha1Digest()); signer.Init(true, pri); signer.BlockUpdate(msg, 0, msg.Length); byte[] sig = signer.GenerateSignature(); Console.WriteLine(Convert.ToBase64String(sig)); signer.Init(false, pub); signer.BlockUpdate(msg, 0, msg.Length); bool valid = signer.VerifySignature(sig); Console.WriteLine(valid); } var priKeyContent = Convert.FromBase64String(@"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKko+TE1xJaRoRm/UrNIoWDejYYPdDurNZe28pXFrRWTyFFPx9ABOx6XduSkbxbmCnh3bqE5ytlpKmZjxVCV74wT9RYMzkmERlBhI55aK6deKNnRS8OluiNyJybT3pxCzKe+daj3P4LgjQLe3d0Jn+bWUT2L0iA/TCdDt6ZLZywVAgMBAAECgYBY7Y5bPW30zehIVdlPIQ6dk0IJSRSMzcvlzyqma/47Cq7TeEKN6ie/RFcfigZQnmzAueCx52TpeKzumOLBI6GDQgnSBx8RVPjx/p8XNGUxw4UQiUG+EW7iNqLEKKKtnwfjYNqFcNAsn1b8CCMORozIwYLhn5ihkBiz10ITQURQoQJBAOBxhfpDYFNhlYHuP3qn7VqKZCzzbAfT6OOuc8GoEJvHeBnKczFrUzMmbiberVn5g/l7rJ9rfakY32f5KYP73XkCQQDA8Z03nqKhqaxdEG2JgStcGgMT1htkWeSmUNoKaY+SBor3BVLrd30VZGp51zzAcTY9pdUG7PQXystxn6Htskh9AkEAhnk+Dp4DvrF/BGQcwH6QpWi5cH1AQshihtflHyh1GwC+IqW7suZc6Q6jfMJ6Fqh6vCWvXaznk0MFx6PvjdZ/8QJBAIZTL7sbK+oUsDUSTNAgJ0m1qlLTCrrwgmjvfP0mxJdLCtAy2qmnxGNyR1aP7HGl37dHjmmF6eHug3iVRCyxpBkCQATsf3oAPErQ0AT2wB0Uof6uv0x+/6r1q0cuR/R3Htd3Sz9GIx+4v79p41DBcSMyr2fubtXp6WiHSlvseiKigWU="); var pubKeyContent = Convert.FromBase64String(@"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpKPkxNcSWkaEZv1KzSKFg3o2GD3Q7qzWXtvKVxa0Vk8hRT8fQATsel3bkpG8W5gp4d26hOcrZaSpmY8VQle+ME/UWDM5JhEZQYSOeWiunXijZ0UvDpbojcicm096cQsynvnWo9z+C4I0C3t3dCZ/m1lE9i9IgP0wnQ7emS2csFQIDAQAB"); //var priKeyContent = Convert.FromBase64String(@"MIICWwIBAAKBgQDsQIuN+M/x9grPYectc3Ye5rboKWT12w9KcSWLgdRlUg9IGe6oDYj/CEGh0rJi4pijlRRY06Ri8MLkn76T/sYYXHuYSzVgAaolhD1Fpv0NwQBBGwWhogz/FF1qhW2dMQiMlBlQjp6jblzbJwnPAg9mESvywj8h03KNG3VnPAhCMwIDAQABAoGAfJsWgA0JcG77CKJ0ke5iEK5TLmQW0e12RSckTE5vvfjoAnla/NwWs5yhMT61w54ML8tDbg5Cl8SwpnDyzZAE3nTX86+oqRUDdJV96YOR2gti6lcfiZYd6qqPgnbZ4KQmcE+LRMpWhnL9zoAdg4kSorHP/nl8UfaRZQqhILg6G4ECQQD/8EOpEq/+M011yLlXMOO496/ckCrfm08DAw9vl0K5FVBMD9Fsd31/7pZh7Um7dqCabaNsYYorbIsffMQXB/6hAkEA7E8SClZJtTE+hUK2Vn9SNTQlofuztui2kRt0lt0+rjqgh+GH3FkPQeVVTQ7dxkq2aUntkEtELso+RRkYgbg0UwJACFF0wX/7/FUKhXN6opzSKebS7mY5Hn9buAtXaxcNchqBO5egBNh1Wb0VYiVmKhOW8K3zi8g3x2WFuAZEEUOPQQJAGTyMiawTbRVYPvUT8gLg7aunBTiTRcpujOqotd/k7Mh4EmrkjoS4W2o5hOQ8jQu3lWD+zPUsz+5rXgfDFT9t3wJACdFWlzj1TC64f9bNo7I2n1S+xWn1Rm/z0e+fVq2n7sbtVtaYQY1HSXPOuDgCKMPcx5Fp1EuhzDvnxIaPdUXzyQ=="); var asn1Seq = Asn1Sequence.GetInstance(priKeyContent); if (asn1Seq is DerSequence) { asn1Seq = (Asn1Sequence)asn1Seq; } var ppriv = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1Seq)) as AsymmetricKeyParameter; var ppubl = PublicKeyFactory.CreateKey((pubKeyContent)); RsaDigestSigner signer1 = new RsaDigestSigner(new Sha1Digest()); signer1.Init(true, ppriv); signer1.BlockUpdate(msg, 0, msg.Length); byte[] sig1 = signer1.GenerateSignature(); Console.WriteLine(Convert.ToBase64String(sig1)); signer1.Init(false, ppubl); signer1.BlockUpdate(msg, 0, msg.Length); bool valid2 = signer1.VerifySignature(sig1); Console.WriteLine(valid2); }
/// <summary> /// Creates a RSA SHA256 signature of <paramref name="data"/> using <paramref name="key"/> /// </summary> /// <param name="key">The key to use when signing</param> /// <param name="data">The data to sign</param> /// <returns>digest signature</returns> public byte[] Sign(AsymmetricKeyParameter key, byte[] data) { signer.Init(true, key); signer.BlockUpdate(data, 0, data.Length); return(signer.GenerateSignature()); }
private byte[] Sign(byte[] bytesToBeSigned) { string alg = null; // Get the set algorithm or infer one try { alg = FindAttribute("alg").AsString(); } catch (Exception) { ; } if (alg == null) { switch (keyToSign.AsString("kty")) { case "RSA": alg = "PS256"; break; case "EC": switch (keyToSign.AsString("crv")) { case "P-256": alg = "ES256"; break; case "P-384": alg = "ES384"; break; case "P-521": alg = "ES512"; break; default: throw new JOSE_Exception("Unknown curve"); } break; default: throw new JOSE_Exception("Unknown or unsupported key type " + keyToSign.AsString("kty")); } objUnprotected.Add("alg", alg); } IDigest digest; IDigest digest2; switch (alg) { case "RS256": case "ES256": case "PS256": case "HS256": digest = new Sha256Digest(); digest2 = new Sha256Digest(); break; case "RS384": case "ES384": case "PS384": case "HS384": digest = new Sha384Digest(); digest2 = new Sha384Digest(); break; case "RS512": case "ES512": case "PS512": case "HS512": digest = new Sha512Digest(); digest2 = new Sha512Digest(); break; case "EdDSA": digest = null; digest2 = null; break; default: throw new JOSE_Exception("Unknown signature algorithm"); } switch (alg) { case "RS256": case "RS384": case "RS512": { RsaDigestSigner signer = new RsaDigestSigner(digest); RsaKeyParameters prv = new RsaPrivateCrtKeyParameters(ConvertBigNum(keyToSign.AsBytes("n")), ConvertBigNum(keyToSign.AsBytes("e")), ConvertBigNum(keyToSign.AsBytes("d")), ConvertBigNum(keyToSign.AsBytes("p")), ConvertBigNum(keyToSign.AsBytes("q")), ConvertBigNum(keyToSign.AsBytes("dp")), ConvertBigNum(keyToSign.AsBytes("dq")), ConvertBigNum(keyToSign.AsBytes("qi"))); signer.Init(true, prv); signer.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); return(signer.GenerateSignature()); } case "PS256": case "PS384": case "PS512": { PssSigner signer = new PssSigner(new RsaEngine(), digest, digest2, digest.GetDigestSize()); RsaKeyParameters prv = new RsaPrivateCrtKeyParameters(ConvertBigNum(keyToSign.AsBytes("n")), ConvertBigNum(keyToSign.AsBytes("e")), ConvertBigNum(keyToSign.AsBytes("d")), ConvertBigNum(keyToSign.AsBytes("p")), ConvertBigNum(keyToSign.AsBytes("q")), ConvertBigNum(keyToSign.AsBytes("dp")), ConvertBigNum(keyToSign.AsBytes("dq")), ConvertBigNum(keyToSign.AsBytes("qi"))); ParametersWithRandom rnd = new ParametersWithRandom(prv, Message.s_PRNG); signer.Init(true, rnd); signer.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); return(signer.GenerateSignature()); } case "ES256": case "ES384": case "ES512": { X9ECParameters p = NistNamedCurves.GetByName(keyToSign.AsString("crv")); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(keyToSign.AsBytes("d")), parameters); ParametersWithRandom param = new ParametersWithRandom(privKey, Message.s_PRNG); ECDsaSigner ecdsa = new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest())); ecdsa.Init(true, param); BigInteger[] sig = ecdsa.GenerateSignature(bytesToBeSigned); byte[] r = sig[0].ToByteArrayUnsigned(); byte[] s = sig[1].ToByteArrayUnsigned(); byte[] sigs = new byte[r.Length + s.Length]; Array.Copy(r, sigs, r.Length); Array.Copy(s, 0, sigs, r.Length, s.Length); return(sigs); } case "HS256": case "HS384": case "HS512": { HMac hmac = new HMac(digest); KeyParameter key = new KeyParameter(keyToSign.AsBytes("k")); byte[] resBuf = new byte[hmac.GetMacSize()]; hmac.Init(key); hmac.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); hmac.DoFinal(resBuf, 0); return(resBuf); } case "EdDSA": switch (keyToSign.AsString("crv")) { case "Ed25519": { ISigner eddsa; Ed25519PrivateKeyParameters privKey = new Ed25519PrivateKeyParameters(keyToSign.AsBytes("d"), 0); eddsa = new Ed25519Signer(); eddsa.Init(true, privKey); eddsa.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); return(eddsa.GenerateSignature()); } } break; } return(null); }
internal byte[] ComputeMac(byte[] bytesToBeSigned, string alg) { IDigest digest; IDigest digest2; byte[] signature; switch (alg) { case "RS256": case "ES256": case "PS256": case "HS256": digest = new Sha256Digest(); digest2 = new Sha256Digest(); break; case "RS384": case "ES384": case "PS384": case "HS384": digest = new Sha384Digest(); digest2 = new Sha384Digest(); break; case "RS512": case "ES512": case "PS512": case "HS512": digest = new Sha512Digest(); digest2 = new Sha512Digest(); break; case "EdDSA": digest = null; digest2 = null; break; default: throw new JoseException("Unknown signature algorithm"); } switch (alg) { case "RS256": case "RS384": case "RS512": { RsaDigestSigner signer = new RsaDigestSigner(digest); RsaKeyParameters prv = new RsaPrivateCrtKeyParameters(ConvertBigNum(this.AsString("n")), ConvertBigNum(this.AsString("e")), ConvertBigNum(this.AsString("d")), ConvertBigNum(this.AsString("p")), ConvertBigNum(this.AsString("q")), ConvertBigNum(this.AsString("dp")), ConvertBigNum(this.AsString("dq")), ConvertBigNum(this.AsString("qi"))); signer.Init(true, prv); signer.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); return(signer.GenerateSignature()); } case "PS256": case "PS384": case "PS512": { PssSigner signer = new PssSigner(new RsaEngine(), digest, digest2, digest.GetDigestSize()); RsaKeyParameters prv = new RsaPrivateCrtKeyParameters(ConvertBigNum(this.AsString("n")), ConvertBigNum(this.AsString("e")), ConvertBigNum(this.AsString("d")), ConvertBigNum(this.AsString("p")), ConvertBigNum(this.AsString("q")), ConvertBigNum(this.AsString("dp")), ConvertBigNum(this.AsString("dq")), ConvertBigNum(this.AsString("qi"))); ParametersWithRandom rnd = new ParametersWithRandom(prv, Message.s_PRNG); signer.Init(true, rnd); signer.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); return(signer.GenerateSignature()); } case "ES256": case "ES384": case "ES512": { digest.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); byte[] o1 = new byte[digest.GetDigestSize()]; digest.DoFinal(o1, 0); X9ECParameters p = NistNamedCurves.GetByName(this.AsString("crv")); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(this.AsString("d")), parameters); ParametersWithRandom param = new ParametersWithRandom(privKey, Message.s_PRNG); ECDsaSigner ecdsa = new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest())); ecdsa.Init(true, param); BigInteger[] sig = ecdsa.GenerateSignature(o1); byte[] r = sig[0].ToByteArrayUnsigned(); byte[] s = sig[1].ToByteArrayUnsigned(); int cbR = (p.Curve.FieldSize + 7) / 8; byte[] sigs = new byte[cbR * 2]; Array.Copy(r, 0, sigs, cbR - r.Length, r.Length); Array.Copy(s, 0, sigs, cbR + cbR - s.Length, s.Length); signature = sigs; return(sigs); } case "HS256": case "HS384": case "HS512": { HMac hmac = new HMac(digest); KeyParameter key = new KeyParameter(this.AsBytes("k")); byte[] resBuf = new byte[hmac.GetMacSize()]; hmac.Init(key); hmac.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); hmac.DoFinal(resBuf, 0); signature = resBuf; return(resBuf); } case "EdDSA": switch (this.AsString("crv")) { case "Ed25519": { ISigner eddsa; Ed25519PrivateKeyParameters privKey = new Ed25519PrivateKeyParameters(this.AsBytes("d"), 0); eddsa = new Ed25519Signer(); eddsa.Init(true, privKey); eddsa.BlockUpdate(bytesToBeSigned, 0, bytesToBeSigned.Length); signature = eddsa.GenerateSignature(); return(signature); } } break; } return(null); }