Beispiel #1
0
        /// <summary>
        /// Export RSA public key
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="format"></param>
        /// <param name="usePemFormat"></param>
        /// <returns></returns>
        public static string ExportPublicKey(this MsRSA rsa, RsaKeyFormat format, bool usePemFormat = false)
        {
            var key = format switch
            {
                RsaKeyFormat.XML => rsa.ExportKeyInLvccXml(false),
                RsaKeyFormat.JSON => rsa.ExportKeyInJson(false),
#if NETCOREAPP3_1 || NETSTANDARD2_1
                RsaKeyFormat.Pkcs1 => BaseConv.ToBase64(rsa.ExportRSAPublicKey()),
                RsaKeyFormat.Pkcs8 => BaseConv.ToBase64(rsa.ExportRSAPublicKey()),
#else
                RsaKeyFormat.Pkcs1 => rsa.GetPublicKeyInPkcs1(),
                RsaKeyFormat.Pkcs8 => rsa.GetPublicKeyInPkcs8(),
#endif
                _ => throw new NotSupportedException("Unknown RSA key type.")
            };

            if (usePemFormat)
            {
                key = format switch
                {
                    RsaKeyFormat.XML => key,
                    RsaKeyFormat.JSON => key,
                    RsaKeyFormat.Pkcs1 => key.RemovePkcs1PublicKeyFormat(),
                    RsaKeyFormat.Pkcs8 => key.RemovePkcs8PublicKeyFormat(),
                    _ => throw new NotSupportedException("Unknown RSA key type.")
                };
            }

            return(key);
        }
Beispiel #2
0
        private void createClientFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (OpenClientFile.ShowDialog(this) == DialogResult.OK)
            {
                List <string> archs = new List <string>();
                List <string> apps  = new List <string>();
                SortedList <string, string> vers = new SortedList <string, string>();

                foreach (string s in UpdateArchitecture.Items)
                {
                    archs.Add(s);
                }
                foreach (string s in UpdateApplication.Items)
                {
                    apps.Add(s);
                }

                Version v = new Version();
                foreach (Update u in listBox1.Items)
                {
                    if (u.Version > v)
                    {
                        v = u.Version;
                    }
                    vers[u.VersionString.ToLower()] = u.VersionString;
                }

                System.Security.Cryptography.RSA cp = System.Security.Cryptography.RSACryptoServiceProvider.Create();
                cp.FromXmlString(m_privateKey);
                string pubkey = cp.ToXmlString(false);

                ClientFileEditor cfe = new ClientFileEditor();
                cfe.Setup(OpenClientFile.FileName, apps, archs, new List <string>(vers.Values), v, pubkey);
            }
        }
        public static System.Security.Cryptography.RSA RsaFromString(string rsaKey)
        {
            Check.Argument.IsNotEmpty(rsaKey, nameof(rsaKey));
            System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();

            rsa.FromJsonString(rsaKey);
            return rsa;
        }
Beispiel #4
0
        private static void FromXml(this System.Security.Cryptography.RSA rsa, string xml)
        {
#if NET45
            rsa.FromXmlString(xml);
#else
            //throws PlatformNotSupportedException
            var csp = ExtractFromXml(xml);
            rsa.ImportParameters(csp);
#endif
        }
Beispiel #5
0
 public RsaCertificate(X509Certificate2 certificate, X509Certificate2Collection chain)
 {
     _certificate      = certificate;
     _privateKey       = _certificate.GetRSAPrivateKey();
     _certificateChain = new byte[chain.Count][];
     for (var i = 0; i < chain.Count; i++)
     {
         _certificateChain[i] = chain[i].RawData;
     }
 }
Beispiel #6
0
        /// <summary>
        /// Validates the public key requirements for a certificate
        /// </summary>
        /// <param name="certificate">Certificate to validate</param>
        /// <returns>True if the certificate's public key is valid within NuGet signature requirements</returns>
        public static bool IsCertificatePublicKeyValid(X509Certificate2 certificate)
        {
            // Check if the public key is RSA with a valid keysize
            System.Security.Cryptography.RSA RSAPublicKey = RSACertificateExtensions.GetRSAPublicKey(certificate);

            if (RSAPublicKey != null)
            {
                return(RSAPublicKey.KeySize >= SigningSpecifications.V1.RSAPublicKeyMinLength);
            }

            return(false);
        }
Beispiel #7
0
        public static (string publicPem, string privatePem) RSAToPem(bool isPKCS8)
        {
            var rsaKey = RsaKey.CreateRsaKey();

            using (System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create())
            {
                rsa.FromJsonString(rsaKey.PrivateKey);

                var publicPem  = RsaProvider.ToPem(rsa, false, isPKCS8);
                var privatePem = RsaProvider.ToPem(rsa, true, isPKCS8);

                return(publicPem, privatePem);
            }
        }
        public static MonoBtlsKey CreateFromRSAPrivateKey(System.Security.Cryptography.RSA privateKey)
        {
            var keyData = MX.PKCS8.PrivateKeyInfo.Encode(privateKey);
            var key     = new MonoBtlsKey(new BoringKeyHandle(mono_btls_key_new()));

            var ret = mono_btls_key_assign_rsa_private_key(key.Handle.DangerousGetHandle(), keyData, keyData.Length);

            if (ret == 0)
            {
                throw new MonoBtlsException("Assigning private key failed.");
            }

            return(key);
        }
        private void IntializeCrypto()
        {
            if (cryptoEngine == null)
            {
                var    tempCryptoEngine = System.Security.Cryptography.RSA.Create();
                byte[] privateKeyBytes  = System.Convert.FromBase64String(privateKeyPem);
                tempCryptoEngine.ImportRSAPrivateKey(privateKeyBytes, out int bytesRead);

                var rsaKeyInfo = tempCryptoEngine.ExportParameters(false);
                var exponent   = ByteArrayToUInt(rsaKeyInfo.Exponent);
                var modulus    = Convert.ToBase64String(rsaKeyInfo.Modulus);
                storedPublicKey = new PublicKey(modulus, exponent);

                cryptoEngine = tempCryptoEngine;
            }
        }
Beispiel #10
0
        public static byte[] AsymmetricEncrypt([NotNull] X509Certificate2 certificate, [NotNull] byte[] data, RSASettings settings = null)
        {
            if (data.Length == 0)
            {
                return(null);
            }
            IAsymmetricAlgorithm asymmetric = null;

            try
            {
                System.Security.Cryptography.RSA algorithm = certificate.GetPublicEncryptor <System.Security.Cryptography.RSA>();
                asymmetric = new RSAAlgorithm <System.Security.Cryptography.RSA>(algorithm);
                return(AsymmetricEncrypt(asymmetric, data, settings));
            }
            finally
            {
                ObjectHelper.Dispose(ref asymmetric);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Import RSA public key
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="format"></param>
        /// <param name="publicKey"></param>
        /// <param name="isPem"></param>
        public static void ImportPublicKey(this MsRSA rsa, RsaKeyFormat format, string publicKey, bool isPem = false)
        {
            if (isPem)
            {
                publicKey = format switch
                {
                    RsaKeyFormat.XML => publicKey,
                    RsaKeyFormat.JSON => publicKey,
                    RsaKeyFormat.Pkcs1 => publicKey.RemovePkcs1PublicKeyFormat(),
                    RsaKeyFormat.Pkcs8 => publicKey.RemovePkcs8PublicKeyFormat(),
                    _ => throw new NotSupportedException("Unknown RSA key type.")
                };
            }

            switch (format)
            {
            case RsaKeyFormat.XML:
                rsa.ImportKeyInLvccXml(publicKey);
                break;

            case RsaKeyFormat.JSON:
                rsa.ImportKeyInJson(publicKey);
                break;

            case RsaKeyFormat.Pkcs1:
#if NETCOREAPP3_1 || NETSTANDARD2_1
                rsa.ImportRSAPublicKey(BaseConv.FromBase64(publicKey), out _);
#else
                rsa.TouchFromPublicKeyInPkcs1(publicKey, out _);
#endif
                break;

            case RsaKeyFormat.Pkcs8:
#if NETCOREAPP3_1 || NETSTANDARD2_1
                rsa.ImportRSAPublicKey(BaseConv.FromBase64(publicKey), out _);
#else
                rsa.TouchFromPublicKeyInPkcs8(publicKey, out _);
#endif
                break;
            }
        }
    }
Beispiel #12
0
        public static bool _Create_System_String( )
        {
            //Parameters
            System.String algName = null;

            //ReturnType/Value
            System.Security.Cryptography.RSA returnVal_Real        = null;
            System.Security.Cryptography.RSA returnVal_Intercepted = null;

            //Exception
            Exception exception_Real        = null;
            Exception exception_Intercepted = null;

            InterceptionMaintenance.disableInterception( );

            try
            {
                returnValue_Real = System.Security.Cryptography.RSA.Create(algName);
            }

            catch (Exception e)
            {
                exception_Real = e;
            }


            InterceptionMaintenance.enableInterception( );

            try
            {
                returnValue_Intercepted = System.Security.Cryptography.RSA.Create(algName);
            }

            catch (Exception e)
            {
                exception_Intercepted = e;
            }


            Return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted));
        }
Beispiel #13
0
        public bool Encrypt(byte[] src, out byte[] dst)
        {
            dst = new byte[src.Length];

            if (key == null)
            {
                key = GetAssemblyHash();
            }

            System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
            aes.Key = key;

            System.Security.Cryptography.ICryptoTransform ict = aes.CreateEncryptor();

            for (int l = 0; l < src.Length;)
            {
                l += ict.TransformBlock(src, l, l + bufferSize < src.Length? bufferSize: src.Length - l, dst, l);
            }

            return(true);
        }
Beispiel #14
0
 public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding)
 {
 }
Beispiel #15
0
 public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.RSA privateKey)
 {
     throw null;
 }
Beispiel #16
0
 public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForRSA(System.Security.Cryptography.RSA key, System.Security.Cryptography.RSASignaturePadding signaturePadding)
 {
     throw null;
 }
 public PublicKey(string keyId, RSAKey rsa)
 {
     Id  = keyId;
     RSA = rsa;
 }
Beispiel #18
0
        public async Task <bool> SignAsync(string packagePath, string outputPath, string timestampUrl, HashAlgorithmName signatureHashAlgorithm, HashAlgorithmName timestampHashAlgorithm, bool overwrite, X509Certificate2 publicCertificate, System.Security.Cryptography.RSA rsa)
        {
            var fileName = Path.GetFileName(packagePath);

            logger.LogInformation($"{nameof(SignAsync)} [{fileName}]: Begin Signing {packagePath}");
            var signatureProvider = new KeyVaultSignatureProvider(rsa, new Rfc3161TimestampProvider(new Uri(timestampUrl)));

            var request = new AuthorSignPackageRequest(publicCertificate, signatureHashAlgorithm, timestampHashAlgorithm);

            string originalPackageCopyPath = null;

            try
            {
                originalPackageCopyPath = CopyPackage(packagePath);

                using (var options = SigningOptions.CreateFromFilePaths(originalPackageCopyPath, outputPath, overwrite, signatureProvider, new NuGetLogger(logger, fileName)))
                {
                    await SigningUtility.SignAsync(options, request, CancellationToken.None);
                }
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
                return(false);
            }
            finally
            {
                try
                {
                    FileUtility.Delete(originalPackageCopyPath);
                }
                catch
                {
                }

                logger.LogInformation($"{nameof(SignAsync)} [{fileName}]: End Signing {packagePath}");
            }

            return(true);
        }
 public void Tests()
 {
     System.Security.Cryptography.RSA rSA = System.Security.Cryptography.RSA.Create();
 }
Beispiel #20
0
 public static byte[] Sign(byte[] content, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, bool isDetached = false)
 {
     throw null;
 }
Beispiel #21
0
 public CertificateRequest(string subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding)
 {
 }
Beispiel #22
0
 public RSAKeyValue(System.Security.Cryptography.RSA key)
 {
 }
 public CoseSigner(System.Security.Cryptography.RSA key, System.Security.Cryptography.RSASignaturePadding signaturePadding, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.Cose.CoseHeaderMap?protectedHeaders = null, System.Security.Cryptography.Cose.CoseHeaderMap?unprotectedHeaders = null)
 {
 }
        public async Task <bool> SignAsync(string packagePath, string outputPath, string timestampUrl, Uri v3ServiceIndex, IReadOnlyList <string> packageOwners,
                                           SignatureType signatureType, HashAlgorithmName signatureHashAlgorithm, HashAlgorithmName timestampHashAlgorithm,
                                           bool overwrite, X509Certificate2 publicCertificate, System.Security.Cryptography.RSA rsa, CancellationToken cancellationToken = default)
        {
            var packagesToSign = LocalFolderUtility.ResolvePackageFromPath(packagePath);

            var signatureProvider = new KeyVaultSignatureProvider(rsa, new Rfc3161TimestampProvider(new Uri(timestampUrl)));

            SignPackageRequest request = null;

            if (signatureType == SignatureType.Author)
            {
                request = new AuthorSignPackageRequest(publicCertificate, signatureHashAlgorithm, timestampHashAlgorithm);
            }
            else if (signatureType == SignatureType.Repository)
            {
                request = new RepositorySignPackageRequest(publicCertificate, signatureHashAlgorithm, timestampHashAlgorithm, v3ServiceIndex, packageOwners);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(signatureType));
            }

            string originalPackageCopyPath = null;

            foreach (var package in packagesToSign)
            {
                cancellationToken.ThrowIfCancellationRequested();
                logger.LogInformation($"{nameof(SignAsync)} [{package}]: Begin Signing {Path.GetFileName(package)}");
                try
                {
                    originalPackageCopyPath = CopyPackage(package);

                    using var options = SigningOptions.CreateFromFilePaths(originalPackageCopyPath, outputPath, overwrite, signatureProvider, new NuGetLogger(logger, package));
                    await SigningUtility.SignAsync(options, request, cancellationToken);
                }
                catch (Exception e)
                {
                    logger.LogError(e, e.Message);
                    return(false);
                }
                finally
                {
                    try
                    {
                        FileUtility.Delete(originalPackageCopyPath);
                    }
                    catch
                    {
                    }

                    logger.LogInformation($"{nameof(SignAsync)} [{package}]: End Signing {Path.GetFileName(package)}");
                }
            }

            return(true);
        }
Beispiel #25
0
 public static byte[] EncryptKey(byte[] keyData, System.Security.Cryptography.RSA rsa, bool useOAEP)
 {
     throw null;
 }
Beispiel #26
0
 public static bool Verify_v15(System.Security.Cryptography.RSA rsa, System.Security.Cryptography.HashAlgorithm hash, byte[] hashValue, byte[] signature, bool tryNonStandardEncoding)
 {
     throw new NotImplementedException();
 }
Beispiel #27
0
 public RSA15(System.Security.Cryptography.RSA key)
     : base(key)
 {
 }
Beispiel #28
0
 public static byte[] ToCapiPublicKeyBlob(System.Security.Cryptography.RSA rsa)
 {
     throw new NotImplementedException();
 }
Beispiel #29
0
 public PublicKey(string keyId, RSAKey rsa)
 {
     this.Id  = keyId;
     this.RSA = rsa;
 }
Beispiel #30
0
 public static byte[] ToCapiKeyBlob(System.Security.Cryptography.RSA rsa, bool includePrivateKey)
 {
     throw new NotImplementedException();
 }