Init() public method

public Init ( bool forSigning, ICipherParameters parameters ) : void
forSigning bool
parameters ICipherParameters
return void
Ejemplo n.º 1
2
        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 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();
 }
Ejemplo n.º 3
0
        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());
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a signature verificator (signature (created on tpm) -> message digest) with the current public key and
        /// for the current algorithm (RSA)
        /// </summary>
        /// <returns></returns>
        public ISigner CreateSignatureVerificator()
        {
            if (_keyParams.AlgorithmId == TPMAlgorithmId.TPM_ALG_RSA && _keyParams.SigScheme == TPMSigScheme.TPM_SS_RSASSAPKCS1v15_SHA1)
            {
                ISigner signer = new RsaDigestSigner(new Sha1Digest());

                /*RsaKeyParameters parameters =
                    new RsaKeyParameters(false,
                                         new BigInteger(1, _publicKey.Pubkey),
                                         new BigInteger(1, ((TPMRSAKeyParams)_keyParams.Params).GetExponent()));
                 */
                signer.Init(false, RsaKeyParameters);

                return signer;
            }
            else
                throw new NotSupportedException(string.Format("SignatureVerificator: Algorithm '{0}' with '{1}' is not supported", _keyParams.AlgorithmId, _keyParams.SigScheme));
        }
Ejemplo n.º 6
0
 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();
 }
Ejemplo n.º 7
0
		private bool VerifyRsa(IDigest digest, byte[] buffer, int length, byte[] signature)
		{
			RsaDigestSigner signer = new RsaDigestSigner(digest);

			int exponentOffset = 1;
			int exponentLength = PublicKey[0] == 0 ? DnsMessageBase.ParseUShort(PublicKey, ref exponentOffset) : PublicKey[0];
			int moduloOffset = exponentOffset + exponentLength;
			int moduloLength = PublicKey.Length - moduloOffset;

			RsaKeyParameters parameters = new RsaKeyParameters(false, new BigInteger(1, PublicKey, moduloOffset, moduloLength), new BigInteger(1, PublicKey, exponentOffset, exponentLength));

			signer.Init(false, new ParametersWithRandom(parameters, _secureRandom));

			signer.BlockUpdate(buffer, 0, length);
			return signer.VerifySignature(signature);
		}
Ejemplo n.º 8
0
		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();
		}
        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();
        }