当前位置: 首页>>代码示例>>C#>>正文


C# Cryptography.RSA类代码示例

本文整理汇总了C#中System.Security.Cryptography.RSA的典型用法代码示例。如果您正苦于以下问题:C# RSA类的具体用法?C# RSA怎么用?C# RSA使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


RSA类属于System.Security.Cryptography命名空间,在下文中一共展示了RSA类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SignXml

        // Sign an XML file.  
        // This document cannot be verified unless the verifying  
        // code has the key with which it was signed. 
        public static void SignXml(XmlDocument xmlDoc, RSA Key)
        {
            // Check arguments. 
            if (xmlDoc == null)
                throw new ArgumentException("xmlDoc");
            if (Key == null)
                throw new ArgumentException("Key");

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "";

            // 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));
        }
开发者ID:duyisu,项目名称:MissionPlanner,代码行数:38,代码来源:SignXML.cs

示例2: CheckStrongSignature

        public bool CheckStrongSignature(RSA publicKey, byte[] tail)
        {
            if (!hasStrongSignature) throw new InvalidOperationException();

            // Hash the whole archive with the SHA1 algorithm
            var sha1 = CommonMethods.SharedSHA1;
            byte[] signature = new byte[2048];

            lock (syncRoot)
            {
                var buffer = new byte[4096];
                long bytesRemaining = archiveDataLength;

                stream.Seek(archiveDataOffset, SeekOrigin.Begin);

                do
                {
                    int count = stream.Read(buffer, 0, bytesRemaining > buffer.Length ? buffer.Length : (int)bytesRemaining);

                    sha1.TransformBlock(buffer, 0, count, null, 0);

                    bytesRemaining -= count;
                }
                while (bytesRemaining > 0);

                sha1.TransformFinalBlock(tail, 0, tail != null ? tail.Length : 0);

                stream.Seek(sizeof(uint), SeekOrigin.Current); // Skip the strong signature header, as it has already been verified earlier

                if (stream.Read(signature, 0, signature.Length) != signature.Length) throw new EndOfStreamException();
            }

            return new RSAPKCS1SignatureDeformatter(publicKey).VerifySignature(sha1, signature);
        }
开发者ID:jhurliman,项目名称:d3research,代码行数:34,代码来源:MpqArchive.Signature.cs

示例3: Decrypt

        /// <summary>
        /// Decrypt binary.
        /// </summary>
        /// <param name="binary">The data to encrypt.</param>
        /// <param name="privateKey">The private key.</param>
        /// <param name="symmetricAlgorithmName">Optional. The name of the symmetric algorithm to use. Defaults to "Rijndael" (128 bits AES). See http://msdn.microsoft.com/en-us/library/k74a682y(v=vs.100).aspx for a list of valid values.</param>
        /// <returns></returns>
        public static byte[] Decrypt(this byte[] binary, RSA privateKey, string symmetricAlgorithmName = "Rijndael")
        {
            if (binary == null) throw new ArgumentNullException("binary");
            if (privateKey == null) throw new ArgumentNullException("privateKey");

            //create sym key of given type
            var symmetricKey = SymmetricAlgorithm.Create(symmetricAlgorithmName);

            if(symmetricKey == null)
                throw new ArgumentException("Unsupported symmetricAlgorithmName: '{0}'".FormatWith(symmetricAlgorithmName), "symmetricAlgorithmName");

            //retrieve encrypted sym key
            var encryptedSymmetricKey = new byte[privateKey.KeySize >> 3];
            Buffer.BlockCopy(binary, 0, encryptedSymmetricKey, 0, encryptedSymmetricKey.Length);

            //decrypt sym key using asym key
            var key = new RSAOAEPKeyExchangeDeformatter(privateKey).DecryptKeyExchange(encryptedSymmetricKey);

            //get IV (public)
            var iv = new byte[symmetricKey.IV.Length];
            Buffer.BlockCopy(binary, encryptedSymmetricKey.Length, iv, 0, iv.Length);

            //decrypt binary using sym key and IV
            return symmetricKey.CreateDecryptor(key, iv).TransformFinalBlock(binary, encryptedSymmetricKey.Length + iv.Length, binary.Length - (encryptedSymmetricKey.Length + iv.Length));
        }
开发者ID:sukchr,项目名称:brevity,代码行数:32,代码来源:ByteArrayExtensions.cs

示例4: SignXmlDocument

        //        /// <summary>
        //        /// Signs a license.
        //        /// </summary>
        //        /// <param name="unsignedLicense"> The unsigned license stream.</param>
        //        /// <param name="keyPair"> The stream containing the private key file.</param>
        //        /// <param name="output"> The output stream containing the new signed license.</param>
        //        internal void SignLicense(XmlTextReader unsignedLicense, Stream keyPair, Stream output)
        //        {
        //            try
        //            {
        //                // setup the document to sign
        //                XmlDocument licenseDocument = new XmlDocument();
        //                licenseDocument.Load(unsignedLicense);
        //
        //                // read in the public key
        //                RSA signingKey = new RSACryptoServiceProvider();
        //                using(StreamReader reader = new StreamReader(keyPair))
        //                {
        //                    signingKey.FromXmlString(reader.ReadLine());
        //                }
        //
        //                // now sign the document
        //                SignedXml signer = new SignedXml(licenseDocument);
        //                signer.SigningKey = signingKey;
        //
        //                // create a reference to the root of the document
        //                Reference orderRef = new Reference("");
        //                orderRef.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        //                signer.AddReference(orderRef);
        //
        //                // add transforms that only select the order items, type, and
        //                // compute the signature, and add it to the document
        //                signer.ComputeSignature();
        //                licenseDocument.DocumentElement.AppendChild(signer.GetXml());
        //
        //                licenseDocument.Save(output);
        //            }
        //            catch
        //            {
        //                throw;
        //            }
        //        }
        /// <summary>
        /// Signs the XmlDocument.
        /// </summary>
        /// <param name="document"> The XmlDocument to sign.</param>
        /// <param name="signingKey"> The signing key.</param>
        /// <returns> A signed XmlDocument.</returns>
        internal XmlDocument SignXmlDocument(XmlDocument document, RSA signingKey)
        {
            try
            {
            //				// setup the document to sign
            //				XmlDocument licenseDocument = new XmlDocument();
            //				licenseDocument.Load(unsignedLicense);

                // now sign the document
                SignedXml signer = new SignedXml(document);
                signer.SigningKey = signingKey;

                // create a reference to the root of the document
                Reference reference = new Reference("");
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                signer.AddReference(reference);

                // compute the signature, and add it to the document
                signer.ComputeSignature();
                document.DocumentElement.AppendChild(signer.GetXml());

                return document;
            }
            catch
            {
                throw;
            }
        }
开发者ID:molekilla,项目名称:Ecyware_GreenBlue_Inspector,代码行数:76,代码来源:XmlSignature.cs

示例5: GenerateCert

        public static X509Certificate2 GenerateCert(string certificateName, RSA key)
        {
            byte[] sn = GenerateSerialNumber();
            string subject = string.Format("CN={0}", certificateName);
            DateTime notBefore = DateTime.Now;
            DateTime notAfter = DateTime.Now.AddYears(20);
            string hashName = "SHA512";

            X509CertificateBuilder cb = new X509CertificateBuilder(3);
            cb.SerialNumber = sn;
            cb.IssuerName = subject;
            cb.NotBefore = notBefore;
            cb.NotAfter = notAfter;
            cb.SubjectName = subject;
            cb.SubjectPublicKey = key;
            cb.Hash = hashName;

            byte[] rawcert = cb.Sign(key);
            PKCS12 p12 = new PKCS12();
            Hashtable attributes = GetAttributes();
            p12.AddCertificate(new Mono.Security.X509.X509Certificate(rawcert), attributes);
            p12.AddPkcs8ShroudedKeyBag(key, attributes);
            rawcert = p12.GetBytes();
            return new X509Certificate2(rawcert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
        }
开发者ID:pkdevboxy,项目名称:couchbase-lite-net,代码行数:25,代码来源:SSLGenerator.cs

示例6: SetKey

        public override void SetKey(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));

            _rsaKey = (RSA)key;
        }
开发者ID:Corillian,项目名称:corefx,代码行数:7,代码来源:RSAPKCS1SignatureFormatter.cs

示例7: StrongNameCertificate

        public StrongNameCertificate(RSA rsa) {
            if (rsa == null) {
                throw new ArgumentNullException("rsa");
            }

            RSA = rsa;
        }
开发者ID:roomaroo,项目名称:coapp.powershell,代码行数:7,代码来源:StrongName.cs

示例8: RsaSecurityKey

        public RsaSecurityKey(RSA rsa)
        {
            if (rsa == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");

            this.rsa = rsa;
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:7,代码来源:RsaSecurityKey.cs

示例9: RsaCryptographicKey

        /// <summary>
        /// Initializes a new instance of the <see cref="RsaCryptographicKey" /> class.
        /// </summary>
        /// <param name="key">The RSA crypto service provider.</param>
        /// <param name="algorithm">The algorithm.</param>
        internal RsaCryptographicKey(RSA key, AsymmetricAlgorithm algorithm)
        {
            Requires.NotNull(key, "key");

            this.key = key;
            this.algorithm = algorithm;
        }
开发者ID:gitter-badger,项目名称:PCLCrypto,代码行数:12,代码来源:RsaCryptographicKey.cs

示例10: VerifyXml

        // Verify the signature of an XML file against an asymmetric
        // algorithm and return the result.
        public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
        {
            // Check arguments.
            if (Doc == null)
                throw new ArgumentException("Doc");
            if (Key == null)
                throw new ArgumentException("Key");

            // Create a new SignedXml object and pass it
            // the XML document class.
            SignedXml signedXml = new SignedXml(Doc);

            // Find the "Signature" node and create a new
            // XmlNodeList object.
            XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

            // Throw an exception if no signature was found.
            if (nodeList.Count <= 0)
            {
                throw new CryptographicException("Verification failed: No Signature was found in the document.");
            }

            //One Sig per document
            if (nodeList.Count >= 2)
            {
                throw new CryptographicException("Verification failed: More that one signature was found for the document.");
            }

            // Load the first <signature> node.
            signedXml.LoadXml((XmlElement)nodeList[0]);

            // Check the signature and return the result.
            return signedXml.CheckSignature(Key);
        }
开发者ID:vpereira,项目名称:sadan,代码行数:36,代码来源:Program.cs

示例11: RSAPKCS1SignatureFormatter

        public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));

            _rsaKey = (RSA)key;
        }
开发者ID:Corillian,项目名称:corefx,代码行数:7,代码来源:RSAPKCS1SignatureFormatter.cs

示例12: VerifyDigitalSignature

        /// <summary>
        /// Verifies the digital signature.
        /// </summary>
        /// <param name="digitalSignature"> The XML Digital Signature.</param>
        /// <param name="publicKey"> The RSA public key.</param>
        /// <returns> Returns true if valid, else false.</returns>
        public static bool VerifyDigitalSignature(XmlTextReader digitalSignature, RSA publicKey)
        {
            bool valid = false;
            try
            {
                // Load license file into XmlDocument
                XmlDocument doc = new XmlDocument();
                doc.Load(digitalSignature);

                // Load Signature Element
                SignedXml verifier = new SignedXml(doc);
                verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement);

                // Validate license.
                if ( verifier.CheckSignature(publicKey) )
                {
                    valid = true;
                }
                else
                {
                    valid = false;
                }
            }
            catch
            {
                valid = false;
            }

            return valid;
        }
开发者ID:molekilla,项目名称:Ecyware_GreenBlue_Inspector,代码行数:36,代码来源:DigitalSignatureVerifier.cs

示例13: S3Storage

        public S3Storage()
        {
            const string filename = "keyxml.pk";
            var path = WebServerPathUtils.GetPathTo(Path.Combine("bin", filename));
            var f = new FileInfo(path);

            if (f.Exists)
            {
                using (var file = f.OpenRead())
                {
                    var keyString = new StreamReader(file).ReadToEnd();
                    _algorithm = RSA.Create();
                    _algorithm.FromXmlString(keyString);

                    var encryptionMaterials = new EncryptionMaterials(_algorithm);
                    try
                    {
                        _client = new AmazonS3EncryptionClient(encryptionMaterials);

                        var bucket = new S3DirectoryInfo(_client, PdfDocumentsBucketName);
                        if (!bucket.Exists)
                        {
                            bucket.Create();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unable to initialize S3 client\n" + ex);
                    }
                }
            }
        }
开发者ID:reactiveui-forks,项目名称:VirtualSales,代码行数:32,代码来源:S3Storage.cs

示例14: SetKey

 public override void SetKey(AsymmetricAlgorithm key) {
     if (key == null) 
         throw new ArgumentNullException("key");
     Contract.EndContractBlock();
     _rsaKey = (RSA) key;
     _rsaOverridesDecrypt = default(bool?);
 }
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:7,代码来源:rsaoaepkeyexchangedeformatter.cs

示例15: SetKey

 public override void SetKey(AsymmetricAlgorithm key)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     this._rsaKey = (RSA) key;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:8,代码来源:RSAPKCS1SignatureDeformatter.cs


注:本文中的System.Security.Cryptography.RSA类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。