Inheritance: AsymmetricAlgorithm
Ejemplo n.º 1
1
        // 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));
        }
Ejemplo n.º 2
0
        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);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <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;
        }
Ejemplo n.º 4
0
        // 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);
        }
        public static int GetMaxRsaEncryptLength(System.Security.Cryptography.RSA rsa, RSAEncryptionPadding padding)
        {
            var offset = 0;

            if (padding.Mode == RSAEncryptionPaddingMode.Pkcs1)
            {
                offset = 11;
            }
            else
            {
                if (padding.Equals(RSAEncryptionPadding.OaepSHA1))
                {
                    offset = 42;
                }

                if (padding.Equals(RSAEncryptionPadding.OaepSHA256))
                {
                    offset = 66;
                }

                if (padding.Equals(RSAEncryptionPadding.OaepSHA384))
                {
                    offset = 98;
                }

                if (padding.Equals(RSAEncryptionPadding.OaepSHA512))
                {
                    offset = 130;
                }
            }
            var keySize   = rsa.KeySize;
            var maxLength = keySize / 8 - offset;

            return(maxLength);
        }
 /// <summary>Constructs a new service account credential using the given initializer.</summary>
 public ServiceAccountCredential(Initializer initializer) : base(initializer)
 {
     id     = initializer.Id.ThrowIfNullOrEmpty("initializer.Id");
     user   = initializer.User;
     scopes = initializer.Scopes;
     key    = initializer.Key.ThrowIfNull("initializer.Key");
 }
Ejemplo n.º 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="subjectName"></param>
        /// <param name="signingCertificate"></param>
        /// <param name="keyUsageExtensions"></param>
        /// <param name="enhancedKeyUsageExtensions"></param>
        /// <returns></returns>
        public static X509Certificate2 SignCertificate(string subjectName, X509Certificate2 signingCertificate, X509KeyUsageExtension keyUsageExtensions, OidCollection enhancedKeyUsageExtensions)
        {
            using (System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create(4096))
            {
                CertificateRequest request = new CertificateRequest(
                    subjectName,
                    rsa,
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(false, false, 0, false));

                request.CertificateExtensions.Add(keyUsageExtensions);

                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        enhancedKeyUsageExtensions,
                        true));

                request.CertificateExtensions.Add(
                    new X509SubjectKeyIdentifierExtension(request.PublicKey, false));

                return(request.Create(signingCertificate, DateTime.UtcNow, DateTime.UtcNow.AddDays(30), new byte[] { 1, 2, 3, 4 }));
            }
        }
Ejemplo n.º 8
0
        public RsaSecurityKey(RSA rsa)
        {
            if (rsa == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");

            this.rsa = rsa;
        }
        /// <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;
        }
Ejemplo n.º 10
0
        public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));

            _rsaKey = (RSA)key;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="data"></param>
        /// <param name="padding"></param>
        /// <returns></returns>
        private static byte[] Encrypt(System.Security.Cryptography.RSA rsa, byte[] data, RSAEncryptionPadding padding = null)
        {
            padding ??= RSAEncryptionPadding.Pkcs1;
            byte[] result;
            var    maxLength = rsa.KeySize / 8 - PaddingLength[padding];

            // 长数据分割
            if (maxLength < data.Length)
            {
                var pointer  = 0;
                var resBytes = new List <byte>();
                while (pointer < data.Length)
                {
                    var length = pointer + maxLength > data.Length ? data.Length - pointer : maxLength;
                    resBytes.AddRange(rsa.Encrypt(data.Skip(pointer).Take(length).ToArray(), padding));
                    pointer += maxLength;
                }
                result = resBytes.ToArray();
            }
            else
            {
                result = rsa.Encrypt(data, padding);
            }
            return(result);
        }
Ejemplo n.º 12
0
        public override void SetKey(AsymmetricAlgorithm key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));

            _rsaKey = (RSA)key;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 验证 XML 文档的数字签名
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
        {
            // Check arguments.
            if (Doc == null)
                throw new ArgumentException("Doc");
            if (Key == null)
                throw new ArgumentException("Key");

            // 创建一个新的 SignedXml 对象,并将 XmlDocument 对象传递给它。
            SignedXml signedXml = new SignedXml(Doc);

            // 找到 <signature> 元素,并创建新的 XmlNodeList 对象。
            XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

            // 如果没有签名,那么抛异常.
            if (nodeList.Count <= 0)
            {
                throw new CryptographicException("Verification failed: No Signature was found in the document.");
            }

            //  如果有多个签名,那么也抛异常.
            if (nodeList.Count >= 2)
            {
                throw new CryptographicException("Verification failed: More that one signature was found for the document.");
            }

            // 将第一个 <signature> 元素的 XML 加载到 SignedXml 对象中。
            signedXml.LoadXml((XmlElement)nodeList[0]);

            // 使用 CheckSignature 方法和 RSA 公钥检查签名。 此方法将返回指示成功或失败的布尔值。
            return signedXml.CheckSignature(Key);
        }
        //        /// <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;
            }
        }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 16
0
        public StrongNameCertificate(RSA rsa) {
            if (rsa == null) {
                throw new ArgumentNullException("rsa");
            }

            RSA = rsa;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// RSA导入key
        /// </summary>
        /// <param name="rsa">RSA实例<see cref="RSA"/></param>
        /// <param name="jsonString">RSA的Key序列化JSON字符串</param>
        internal static void FromJsonString(this System.Security.Cryptography.RSA rsa, string jsonString)
        {
            Check.Argument.IsNotEmpty(jsonString, nameof(jsonString));

            RSAParameters parameters = new RSAParameters();

            try
            {
                var paramsJson = JsonConvert.DeserializeObject <RSAParametersJson>(jsonString);

                parameters.Modulus = paramsJson.Modulus != null?Convert.FromBase64String(paramsJson.Modulus) : null;

                parameters.Exponent = paramsJson.Exponent != null?Convert.FromBase64String(paramsJson.Exponent) : null;

                parameters.P = paramsJson.P != null?Convert.FromBase64String(paramsJson.P) : null;

                parameters.Q = paramsJson.Q != null?Convert.FromBase64String(paramsJson.Q) : null;

                parameters.DP = paramsJson.DP != null?Convert.FromBase64String(paramsJson.DP) : null;

                parameters.DQ = paramsJson.DQ != null?Convert.FromBase64String(paramsJson.DQ) : null;

                parameters.InverseQ = paramsJson.InverseQ != null?Convert.FromBase64String(paramsJson.InverseQ) : null;

                parameters.D = paramsJson.D != null?Convert.FromBase64String(paramsJson.D) : null;
            }
            catch
            {
                throw new Exception("Invalid Json RSA key.");
            }
            rsa.ImportParameters(parameters);
        }
        public static void TouchFromPrivateKeyInPkcs1(this MsRSA rsa, string privateKey, out RSAParameters parameters)
        {
            var pr = new PemReader(new StringReader(privateKey.RemovePkcs1PrivateKeyFormat()));

            if (!(pr.ReadObject() is AsymmetricCipherKeyPair asymmetricCipherKeyPair))
            {
                throw new Exception("Private key format is incorrect");
            }

            var rsaPrivateCrtKeyParameters = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(
                PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricCipherKeyPair.Private));

            parameters = new RSAParameters
            {
                Modulus  = rsaPrivateCrtKeyParameters.Modulus.ToByteArrayUnsigned(),
                Exponent = rsaPrivateCrtKeyParameters.PublicExponent.ToByteArrayUnsigned(),
                P        = rsaPrivateCrtKeyParameters.P.ToByteArrayUnsigned(),
                Q        = rsaPrivateCrtKeyParameters.Q.ToByteArrayUnsigned(),
                DP       = rsaPrivateCrtKeyParameters.DP.ToByteArrayUnsigned(),
                DQ       = rsaPrivateCrtKeyParameters.DQ.ToByteArrayUnsigned(),
                InverseQ = rsaPrivateCrtKeyParameters.QInv.ToByteArrayUnsigned(),
                D        = rsaPrivateCrtKeyParameters.Exponent.ToByteArrayUnsigned()
            };

            rsa.ImportParameters(parameters);
        }
Ejemplo n.º 19
0
        /// <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));
        }
 public override void SetKey(AsymmetricAlgorithm key) {
     if (key == null) 
         throw new ArgumentNullException("key");
     Contract.EndContractBlock();
     _rsaKey = (RSA) key;
     _rsaOverridesDecrypt = default(bool?);
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Signiert ein Xml-Document.
        /// </summary>
        /// <param name="xDoc">Das Dokument welches die Daten enthält die signiert werden sollen.</param>
        /// <param name="privateKey">Der private Schlüssel.</param>
        /// <returns>Gibt ein Xml Element mit den Signierten daten zurück.</returns>
        public static XmlElement SignXmlDocument(XmlDocument xDoc, string privateKey)
        {
            var signedXml = new SignedXml();

            System.Security.Cryptography.RSA pvk = System.Security.Cryptography.RSA.Create();
            pvk.FromXmlString(privateKey);
            signedXml.SigningKey = pvk;

            var dataObject = new DataObject();

            dataObject.Id   = "content";
            dataObject.Data = xDoc.ChildNodes;

            signedXml.AddObject(dataObject);

            var reference = new Reference();

            reference.Uri = "#content";

            signedXml.AddReference(reference);

            var keyinfo = new KeyInfo();

            keyinfo.AddClause(new RSAKeyValue(pvk));
            signedXml.KeyInfo = keyinfo;

            signedXml.ComputeSignature();

            return(signedXml.GetXml());
        }
Ejemplo n.º 22
0
        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);
        }
Ejemplo n.º 23
0
 public StrongName(System.Security.Cryptography.RSA rsa)
 {
     if (rsa == null)
     {
         throw new ArgumentNullException("rsa");
     }
     this.RSA = rsa;
 }
 internal Initializer(ServiceAccountCredential other) : base(other)
 {
     Id        = other.Id;
     ProjectId = other.ProjectId;
     User      = other.User;
     Scopes    = other.Scopes;
     Key       = other.Key;
 }
Ejemplo n.º 25
0
 public Product()
 {
     _key = RSA.Create();
     _id = Guid.NewGuid();
     _issuedLicenses = new ObservableCollection<License>();
     _publicKey = _key.ToXmlString(false);
     _privateKey = _key.ToXmlString(true);
 }
            /// <summary>Extracts the <see cref="Key"/> from the given PKCS8 private key.</summary>
            public Initializer FromPrivateKey(string privateKey)
            {
                RSAParameters rsaParameters = Pkcs8.DecodeRsaParameters(privateKey);

                Key = (RsaKey)RSA.Create();
                Key.ImportParameters(rsaParameters);
                return(this);
            }
Ejemplo n.º 27
0
 /// <summary>
 /// Erstellt ein neues Schlüsselpaar
 /// </summary>
 /// <returns></returns>
 public static string[] CreateNewKeys()
 {
     System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
     return(new[] {
         rsa.ToXmlString(true),                         //PrivateKey
         rsa.ToXmlString(false)                         //PublicKey
     });
 }
 public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     this._rsaKey = (RSA) key;
 }
 public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     this._rsaKey = (RSA) key;
 }
 public override void SetKey(AsymmetricAlgorithm key)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     this._rsaKey = (RSA) key;
 }
 public bool Matches(RSA rsa)
 {
     if (rsa == null)
     {
         return false;
     }
     RSAParameters parameters = rsa.ExportParameters(false);
     return (System.IdentityModel.SecurityUtils.MatchesBuffer(this.rsaParameters.Modulus, parameters.Modulus) && System.IdentityModel.SecurityUtils.MatchesBuffer(this.rsaParameters.Exponent, parameters.Exponent));
 }
Ejemplo n.º 32
0
        public static LongRSACryptKey GetLongRSACryptKeyFromEncryptedAES(ReadOnlySpan <Byte> encryptedkey, ReadOnlySpan <Byte> encryptediv,
                                                                         ReadOnlySpan <Byte> privatekey, RSAKeyType type = Cryptography.RSA.DefaultRSAKeyType, RSAParameters?parameters = null)
        {
            Rsa rsa = Cryptography.RSA.Create(privatekey, type, parameters);
            ReadOnlySpan <Byte> key = rsa.Decrypt(encryptedkey.ToArray());
            ReadOnlySpan <Byte> iv  = rsa.Decrypt(encryptediv.ToArray());

            return(new LongRSACryptKey(key, iv));
        }
Ejemplo n.º 33
0
		public void SetUp () 
		{
			if (rsa == null) {
				rsa = RSA.Create ();
				rsa.ImportParameters (AllTests.GetRsaKey (true));
			}
			if (dsa == null)
				dsa = DSA.Create ();
		}
Ejemplo n.º 34
0
    /// <summary>
    /// 把java的公钥转换成.net的xml格式,java->.net
    /// </summary>
    /// <param name="privateKey">java提供的第三方公钥</param>
    /// <returns></returns>
    public static string ConvertToXmlPublicJavaKey(this System.Security.Cryptography.RSA rsa, string publicJavaKey)
    {
        RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicJavaKey));
        string           xmlpublicKey   = string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
                                                        Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
                                                        Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));

        return(xmlpublicKey);
    }
 /// <summary>
 /// Creates a new instance of <see cref="RsaEncryptionCookieTransform"/>
 /// </summary>
 /// <param name="certificate">Certificate whose private key is used to encrypt and decrypt.</param>
 /// <exception cref="ArgumentNullException">When certificate is null.</exception>
 /// <exception cref="ArgumentException">When the certificate has no private key.</exception>
 /// <exception cref="ArgumentException">When the certificate's key is not RSA.</exception>
 public RsaEncryptionCookieTransform( X509Certificate2 certificate )
 {
     if ( null == certificate )
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "certificate" );
     }
     _encryptionKey = X509Util.EnsureAndGetPrivateRSAKey( certificate );
     _decryptionKeys.Add( _encryptionKey );
 }
Ejemplo n.º 36
0
 public Saml2EncryptedXml(XmlDocument document, RSA decryptionPrivateKey)
     : this(document)
 {
     if (decryptionPrivateKey == null)
     {
         throw new ArgumentNullException("decryptionPrivateKey");
     }
     DecryptionPrivateKey = decryptionPrivateKey;
 }
Ejemplo n.º 37
0
 public RSA(int keysize)
 {
     _rsa         = System.Security.Cryptography.RSA.Create();
     _rsa.KeySize = keysize;//默认是2048,也就是_parameter.Modulus是256字节,但是js那边的算法会卡死
     //把公钥适当转换,准备发往客户端
     _parameter   = _rsa.ExportParameters(true);
     _KeyExponent = BytesToHexString(_parameter.Exponent);
     _KeyModulus  = BytesToHexString(_parameter.Modulus);
 }
 /// <summary>
 /// Creates a new instance of <see cref="RsaEncryptionCookieTransform"/>.
 /// </summary>
 /// <param name="key">The provided key will be used as the encryption and decryption key by default.</param>
 /// <exception cref="ArgumentNullException">When the key is null.</exception>
 public RsaEncryptionCookieTransform( RSA key )
 {
     if ( null == key )
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "key" );
     }
     _encryptionKey = key;
     _decryptionKeys.Add( _encryptionKey );
 }
	public void SetUp () 
	{
		sig = new SignatureDescription();
		// key generation is VERY long so one time is enough
		if (dsa == null)
			dsa = DSA.Create ();
		if (rsa == null)
			rsa = RSA.Create ();
	}
 /// <summary>
 /// Creates a new instance of <see cref="RsaSignatureCookieTransform"/>
 /// </summary>
 /// <param name="certificate">Certificate whose private key is used to sign and verify.</param>
 /// <exception cref="ArgumentNullException">When certificate is null.</exception>
 /// <exception cref="ArgumentException">When the certificate has no private key.</exception>
 /// <exception cref="ArgumentException">When the certificate's key is not RSA.</exception>
 public RsaSignatureCookieTransform(X509Certificate2 certificate)
 {
     if (null == certificate)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
     }
     _signingKey = X509Util.EnsureAndGetPrivateRSAKey(certificate);
     _verificationKeys.Add(_signingKey);
 }
  /// <summary>
 /// Creates a new instance of <see cref="RsaSignatureCookieTransform"/>.
 /// </summary>
 /// <param name="key">The provided key will be used as the signing and verification key by default.</param>
 /// <exception cref="ArgumentNullException">When the key is null.</exception>
 public RsaSignatureCookieTransform(RSA key)
 {
     if (null == key)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
     }
     _signingKey = key;
     _verificationKeys.Add(_signingKey);
 }
        /// <summary>
        /// Constructs a proof token based on RSA key.
        /// </summary>
        /// <param name="rsaAlgorithm"></param>
        public AsymmetricProofDescriptor( RSA rsaAlgorithm )
        {
            if ( rsaAlgorithm == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "rsaAlgorithm" );
            }

            _keyIdentifier = new SecurityKeyIdentifier(new RsaKeyIdentifierClause(rsaAlgorithm));
        }
        public bool Matches(RSA rsa)
        {
            if (rsa == null)
                return false;

            RSAParameters rsaParameters = rsa.ExportParameters(false);
            return SecurityUtils.MatchesBuffer(this.rsaParameters.Modulus, rsaParameters.Modulus) &&
                SecurityUtils.MatchesBuffer(this.rsaParameters.Exponent, rsaParameters.Exponent);
        }
        public RsaKeyIdentifierClause(RSA rsa)
            : base(clauseType)
        {
            if (rsa == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");

            this.rsa = rsa;
            this.rsaParameters = rsa.ExportParameters(false);
        }
Ejemplo n.º 45
0
 public byte[] sign()
 {
     SSC.RSA rsa = SSC.RSA.Create();
     rsa.ImportParameters(RSAparams);
     SSC.RSAPKCS1SignatureFormatter signer = new SSC.RSAPKCS1SignatureFormatter(rsa);
     signer.SetHashAlgorithm("SHA1");
     sc.Close();
     return(signer.CreateSignature(md.Hash));
 }
Ejemplo n.º 46
0
 public void Dispose()
 {
     if (_rsa != null)
     {
         _rsa.Dispose();
         _rsa = null;
     }
     _parameter   = new RSAParameters();
     _KeyExponent = null;
     _KeyModulus  = null;
 }
Ejemplo n.º 47
0
    /// <summary>
    /// RSA公钥格式转换,.net->java
    /// </summary>
    /// <param name="publicCSharpKey">.net生成的公钥</param>
    /// <returns></returns>
    public static string ConvertToJavaPublicKey(this System.Security.Cryptography.RSA rsa, string publicCSharpKey)
    {
        XmlDocument          doc           = new XmlDocument(); doc.LoadXml(publicCSharpKey);
        BigInteger           m             = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
        BigInteger           p             = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
        RsaKeyParameters     pub           = new RsaKeyParameters(false, m, p);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);

        byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
        return(Convert.ToBase64String(serializedPublicBytes));
    }
Ejemplo n.º 48
0
        public static void ImportFromXmlString(this System.Security.Cryptography.RSA rsa, string filename)
        {
            var parameters = new RSAParameters();
            var xmlDoc     = new XmlDocument();

            xmlDoc.Load(filename);
            if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue"))
            {
                foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
                {
                    switch (node.Name)
                    {
                    case "Modulus":
                        parameters.Modulus = Convert.FromBase64String(node.InnerText);
                        break;

                    case "Exponent":
                        parameters.Exponent = Convert.FromBase64String(node.InnerText);
                        break;

                    case "P":
                        parameters.P = Convert.FromBase64String(node.InnerText);
                        break;

                    case "Q":
                        parameters.Q = Convert.FromBase64String(node.InnerText);
                        break;

                    case "DP":
                        parameters.DP = Convert.FromBase64String(node.InnerText);
                        break;

                    case "DQ":
                        parameters.DQ = Convert.FromBase64String(node.InnerText);
                        break;

                    case "InverseQ":
                        parameters.InverseQ = Convert.FromBase64String(node.InnerText);
                        break;

                    case "D":
                        parameters.D = Convert.FromBase64String(node.InnerText);
                        break;
                    }
                }
            }
            else
            {
                throw new Exception("Invalid XML RSA key.");
            }

            rsa.ImportParameters(parameters);
        }
            /// <summary>Extracts the <see cref="Key"/> from the given PKCS8 private key.</summary>
            public Initializer FromPrivateKey(string privateKey)
            {
#if NETSTANDARD
                RsaPrivateCrtKeyParameters parameters = ConvertPKCS8ToRsaPrivateCrtKeyParameters(privateKey);
                Key = new RsaStandard(parameters);
#else
                RSAParameters rsaParameters = ConvertPKCS8ToRSAParameters(privateKey);
                Key = new RSACryptoServiceProvider();
                Key.ImportParameters(rsaParameters);
#endif
                return(this);
            }
Ejemplo n.º 50
0
        internal bool VerifySignature(System.Security.Cryptography.RSA rsa)
        {
            RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(rsa);
            string signaturealgo = this.m_signaturealgo;

            if (signaturealgo != null)
            {
                if (__f__switch_map11 == null)
                {
                    Dictionary <string, int> dictionary = new Dictionary <string, int>(4)
                    {
                        {
                            "1.2.840.113549.1.1.2",
                            0
                        },
                        {
                            "1.2.840.113549.1.1.4",
                            1
                        },
                        {
                            "1.2.840.113549.1.1.5",
                            2
                        },
                        {
                            "1.3.14.3.2.29",
                            2
                        }
                    };
                    __f__switch_map11 = dictionary;
                }
                if (__f__switch_map11.TryGetValue(signaturealgo, out int num))
                {
                    switch (num)
                    {
                    case 0:
                        deformatter.SetHashAlgorithm("MD2");
                        goto Label_00CA;

                    case 1:
                        deformatter.SetHashAlgorithm("MD5");
                        goto Label_00CA;

                    case 2:
                        deformatter.SetHashAlgorithm("SHA1");
                        goto Label_00CA;
                    }
                }
            }
            throw new CryptographicException("Unsupported hash algorithm: " + this.m_signaturealgo);
Label_00CA:
            return(deformatter.VerifySignature(this.Hash, this.Signature));
        }
            /// <summary>Extracts a <see cref="Key"/> from the given certificate.</summary>
            public Initializer FromCertificate(X509Certificate2 certificate)
            {
#if NETSTANDARD
                Key = certificate.GetRSAPrivateKey();
#else
                // Workaround to correctly cast the private key as a RSACryptoServiceProvider type 24.
                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
                byte[] privateKeyBlob        = rsa.ExportCspBlob(true);
                Key = new RSACryptoServiceProvider();
                Key.ImportCspBlob(privateKeyBlob);
#endif
                return(this);
            }
        public static void TouchFromPublicKeyInPkcs8(this MsRSA rsa, string publicKey, out RSAParameters parameters)
        {
            var publicKeyBytes = BaseConv.FromBase64(publicKey.RemovePkcs8PublicKeyFormat());
            var publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKeyBytes);

            parameters = new RSAParameters
            {
                Modulus  = publicKeyParam.Modulus.ToByteArrayUnsigned(),
                Exponent = publicKeyParam.Exponent.ToByteArrayUnsigned()
            };

            rsa.ImportParameters(parameters);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                rsa = null;
            }

            disposed = true;
        }
Ejemplo n.º 54
0
        /// <summary>
        /// 获取RSA Key序列化XML
        /// </summary>
        /// <param name="rsa">RSA实例<see cref="RSA"/></param>
        /// <param name="includePrivateParameters">是否包含私钥</param>
        /// <returns></returns>
        public static string ToLvccXmlString(this System.Security.Cryptography.RSA rsa, bool includePrivateParameters)
        {
            RSAParameters parameters = rsa.ExportParameters(includePrivateParameters);

            return(string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                                 parameters.Modulus != null ? Convert.ToBase64String(parameters.Modulus) : null,
                                 parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null,
                                 parameters.P != null ? Convert.ToBase64String(parameters.P) : null,
                                 parameters.Q != null ? Convert.ToBase64String(parameters.Q) : null,
                                 parameters.DP != null ? Convert.ToBase64String(parameters.DP) : null,
                                 parameters.DQ != null ? Convert.ToBase64String(parameters.DQ) : null,
                                 parameters.InverseQ != null ? Convert.ToBase64String(parameters.InverseQ) : null,
                                 parameters.D != null ? Convert.ToBase64String(parameters.D) : null));
        }
        /// <summary>
        /// RSA Verify
        /// </summary>
        /// <param name="content">raw content</param>
        /// <param name="signStr">sign str</param>
        /// <param name="publickKey">public key</param>
        /// <param name="hashAlgorithmName">hashAlgorithm name</param>
        /// <param name="rSASignaturePadding">ras siginature padding</param>
        /// <param name="encoding">text encoding</param>
        /// <returns></returns>
        public static bool RSAVerify(string content, string signStr, string publickKey, HashAlgorithmName hashAlgorithmName, RSASignaturePadding rSASignaturePadding, Encoding encoding)
        {
            Check.Argument.IsNotEmpty(content, nameof(content));
            Check.Argument.IsNotEmpty(signStr, nameof(signStr));

            byte[] dataBytes = encoding.GetBytes(content);
            byte[] signBytes = Convert.FromBase64String(signStr);

            using (System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create())
            {
                rsa.FromJsonString(publickKey);
                return(rsa.VerifyData(dataBytes, signBytes, hashAlgorithmName, rSASignaturePadding));
            }
        }
Ejemplo n.º 56
0
 internal static byte[] WrapSecretKey(System.Security.Cryptography.RSA publicKey, byte[] keyBytes, String oaepDigestAlgorithm)
 {
     try
     {
         return(publicKey.Encrypt(keyBytes,
                                  "SHA-256".Equals(oaepDigestAlgorithm)
                 ? RSAEncryptionPadding.OaepSHA256
                 : RSAEncryptionPadding.OaepSHA512));
     }
     catch (Exception e)
     {
         throw new EncryptionException("Failed to wrap secret key!", e);
     }
 }
Ejemplo n.º 57
0
        private static string Rsa(string data, string privateKeyPem, string charset, string signType, bool keyFromFile)
        {
            byte[] signatureBytes = null;
            try
            {
                System.Security.Cryptography.RSA rsaCsp = null;
                if (keyFromFile)
                {
                    //文件读取
                    rsaCsp = LoadCertificateFile(privateKeyPem, signType);
                }
                else
                {
                    //字符串获取
                    rsaCsp = LoadCertificateString(privateKeyPem, signType);
                }

                byte[] dataBytes = null;

                if (string.IsNullOrEmpty(charset))
                {
                    dataBytes = Encoding.UTF8.GetBytes(data);
                }
                else
                {
                    dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
                }

                if (null == rsaCsp)
                {
                    throw new SpearPayException("您使用的私钥格式错误,请检查RSA私钥配置" + ",charset = " + charset);
                }

                if ("RSA2".Equals(signType))
                {
                    signatureBytes = rsaCsp.SignData(dataBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                }
                else
                {
                    signatureBytes = rsaCsp.SignData(dataBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
                }
            }
            catch
            {
                throw new SpearPayException("您使用的私钥格式错误,请检查RSA私钥配置" + ",charset = " + charset);
            }

            return(Convert.ToBase64String(signatureBytes));
        }
Ejemplo n.º 58
0
        public RSA(RSAType rsaType, System.Text.Encoding encoding, string privateKey, string publicKey = null)
        {
            _encoding = encoding;
            if (!string.IsNullOrEmpty(privateKey))
            {
                _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
            }

            if (!string.IsNullOrEmpty(publicKey))
            {
                _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
            }

            _hashAlgorithmName = rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256;
        }
Ejemplo n.º 59
0
        public static string Encrypt(string encryptString, String key)
        {
            System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
            RSAParameters para = new RSAParameters();

            byte[] b1 = null;
            byte[] b2 = null;
            ResolveKey(key, out b1, out b2);
            para.Exponent = b1;
            para.Modulus  = b2;
            rsa.ImportParameters(para);

            byte[] enBytes = rsa.Encrypt(Encoding.UTF8.GetBytes(encryptString), RSAEncryptionPadding.Pkcs1);
            return(bytes2hex(enBytes));
        }
        public static string GetPublicKeyInPkcs1(this MsRSA rsa)
        {
            var privateKeyParameters = rsa.ExportParameters(false);
            var rsaKeyParameters     = new RsaKeyParameters(
                false,
                new BigInteger(1, privateKeyParameters.Modulus),
                new BigInteger(1, privateKeyParameters.Exponent));

            using var writer = new StringWriter();
            var pemWriter = new PemWriter(writer);

            pemWriter.WriteObject(rsaKeyParameters);
            pemWriter.Writer.Close();
            return(writer.ToString());
        }