working on it ...

Filters

Explore Public Snippets

Sort by

Found 86 snippets matching: x509

    public by cghersi  2694  0  5  0

    Transform a JKS keystore in a PEM certificate

    This set of commands transform the certificate from a JKS to a PEM format. It requires JDK keytool and openssl.
    keytool -keystore client.ts -exportcert -alias mobile | openssl x509 -inform der -text
    
    #psw of keystore: changeit
    
    keytool -importkeystore -srckeystore client.ts -destkeystore client.p12 -srcstoretype jks -deststoretype pkcs12
    
    #psw of destination keystore: changeit
    
    openssl pkcs12 -in client.p12 -out client.pem
    
    #import psw: changeit

    public by msdn  183610  0  6  0

    SelectManagementCertFile: Return a collection of installed X509Certificates from standard X509Certificate dialogue window

    Return a collection of installed X509Certificates from standard X509Certificate dialogue window
    using System;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Cryptography;
    using Microsoft.ComputeCluster.Management.Win32Helpers;
    using System.Collections.Generic;
    
    /// <summary>
    /// Return a collection of installed X509Certificates from standard X509Certificate dialogue window
    /// </summary>
    /// <returns></returns>
    public static X509Certificate2Collection SelectManagementCertFile()
    {
        X509Certificate2Collection certs = X509Certificate2UI.SelectFromCollection(GetValidCertificates(),
                                           "Select a Windows Azure Management Certificate",
                                           "",
                                           X509SelectionFlag.SingleSelection);
        return certs;
    }

    public by msdn  112512  0  5  0

    CertificateServiceKeyCRUD: CRUD for service key of 'X509Certificate' key type.

    CRUD for service key of 'X509Certificate' key type.
    /// <summary>
    /// CRUD for service key of 'X509Certificate' key type. 
    /// </summary>
    private static void CertificateServiceKeyCRUD()
    {
        string displayName = "Certificate for signing tokens to RPs";
    
        // Add a signing certificate. 
        {
            string pfxFileName = "SampleCert.pfx";
            string protectionPassword = @"pass@word1";
    
            byte[] signingCertificate = ManagementServiceHelper.ReadBytesFromPfxFile(pfxFileName, protectionPassword);
    
            EnumerateServiceKeys();
    
            DeleteServiceKeyByDisplayNameIfExists(displayName);
            EnumerateServiceKeys();
    
            AddServiceKey(displayName, signingCertificate, protectionPassword, ServiceKeyType.X509Certificate, ServiceKeyUsage.Signing);
            EnumerateServiceKeys();
        }
    
        // Update and delete the signing certificate. 
        {
            string pfxFileName2 = "TenantSigningCert.pfx";
            string protectionPassword2 = @"TenantSigningCert";
    
            byte[] updatedSigningCertificate = ManagementServiceHelper.ReadBytesFromPfxFile(pfxFileName2, protectionPassword2);
    
            UpdateServiceKey(displayName, updatedSigningCertificate, protectionPassword2, ServiceKeyType.X509Certificate);
            EnumerateServiceKeys();
    
            DeleteServiceKeyByDisplayNameIfExists(displayName);
            EnumerateServiceKeys();
        }
    }

    public by msdn  2923  3  7  0

    FindCertificate: Find a X509 certificate of matching thumbprint or SubjectName from the LocalMachine/My certificate store and LocalMachine/Personal store

    Find a X509 certificate of matching thumbprint or SubjectName from the LocalMachine/My certificate store and LocalMachine/Personal store content of ThumbPrint or SubjectName ThumbPrint or SubjectName an X509Certificate2 object
    using System;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Cryptography;
    using Microsoft.ComputeCluster.Management.Win32Helpers;
    using System.Collections.Generic;
    
    /// <summary>
    /// Find a X509 certificate of matching thumbprint or SubjectName from the LocalMachine/My
    /// certificate store and LocalMachine/Personal store
    /// </summary>
    /// <param name="str">content of ThumbPrint or SubjectName</param>
    /// <param name="type">ThumbPrint or SubjectName</param>
    /// <returns>an X509Certificate2 object</returns>
    public static X509Certificate2 FindCertificate(string str, FindType type)
    {
        // Find certificate for personal store
        X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
    
        X509Certificate2Collection collection;
        try
        {
            if (type == FindType.Thumbprint)
            {
                collection = store.Certificates.Find(X509FindType.FindByThumbprint, str, true);
            }
            else
            {
                collection = store.Certificates.Find(X509FindType.FindBySubjectName, str, true);
            }
    
            if (collection != null && collection.Count > 0)
            {
                if (collection[0].HasPrivateKey)
                {
                    return collection[0];
                }
            }
        }
        finally
        {
            store.Close();
        }
    
        string err = string.Format("No private key certificate that matches thumbprint or SubjectName {0} could be found in the personal certificate store of the current user or the local computer. For more information, see http://go.microsoft.com/fwlink/?LinkId=228597.", str);
        throw new InvalidOperationException(err);
    }

    public by msdn  2248  2  7  0

    SignData: Sign the data with the X509Certificate

    Sign the data with the X509Certificate Signing certificate. Data to be signed. RSA SHA 256 Signature
    /// <summary>
    /// Sign the data with the X509Certificate
    /// </summary>
    /// <param name="signingCertificate">Signing certificate.</param>
    /// <param name="data">Data to be signed.</param>
    /// <returns>RSA SHA 256 Signature</returns>
    public static byte[] SignData(X509Certificate2 signingCertificate, string data)
    {
        X509AsymmetricSecurityKey securityKey = new X509AsymmetricSecurityKey(signingCertificate);
    
        RSACryptoServiceProvider rsa =
            securityKey.GetAsymmetricAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", true)
            as RSACryptoServiceProvider;
    
        if (!signingCertificate.HasPrivateKey)
        {
            throw new ArgumentException(string.Format(
                "Private key is not found in the certificate: {0}",
                signingCertificate.Subject));
        }
    
        rsa.FromXmlString(signingCertificate.PrivateKey.ToXmlString(true));
    
        if (rsa.CspKeyContainerInfo.ProviderType != 24)
        {
            System.Security.Cryptography.CspParameters cspParameters =
                new System.Security.Cryptography.CspParameters();
            cspParameters.ProviderType = 24;
            cspParameters.KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName;
            cspParameters.KeyNumber = (int)rsa.CspKeyContainerInfo.KeyNumber;
    
            if (rsa.CspKeyContainerInfo.MachineKeyStore)
            {
                cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
            }
    
            rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters);
        }
    
        HashAlgorithm hashAlgo = System.Security.Cryptography.SHA256.Create();
        byte[] signatureInBytes = rsa.SignData(Encoding.UTF8.GetBytes(data), hashAlgo);
    
        return signatureInBytes;
    }

    public by msdn  1614  1  7  0

    CreateCertFile: Create .cer or .pfx file from an X509Certificate2 object

    Create .cer or .pfx file from an X509Certificate2 object an X509Certificate2 object name of generated .cer file full path of newly generated .cer file
    using System;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Cryptography;
    using Microsoft.ComputeCluster.Management.Win32Helpers;
    using System.Collections.Generic;
    
    // Default password for generating .pfx file
    // users can change according to their real application
    private const string PasswordForCert = "password";
    
    /// <summary>
    /// Create .cer or .pfx file from an X509Certificate2 object
    /// </summary>
    /// <param name="cert">an X509Certificate2 object</param>
    /// <param name="NewCerFile">name of generated .cer file</param>
    /// <returns>full path of newly generated .cer file</returns>
    public static string CreateCertFile(X509Certificate2 cert, string NewCertFile, CertFileType certFileType)
    {
        byte[] CerContents;
    
        // Write the content to a local .cer file so that users can upload it into Azure 
        if (certFileType == CertFileType.Cer)
        {
            CerContents = cert.Export(X509ContentType.Cert);
        }
        else
        {
            CerContents = cert.Export(X509ContentType.Pfx, PasswordForCert);
        }
    
        using (FileStream fileStream = new FileStream(NewCertFile, FileMode.Create))
        {
    
            for (int i = 0; i < CerContents.Length; i++)
            {
                fileStream.WriteByte(CerContents[i]);
            }
    
            fileStream.Seek(0, SeekOrigin.Begin);
            fileStream.Close();
        }
    
        return System.IO.Path.GetFullPath(NewCertFile);
    }

    public by msdn  1481  2  6  0

    GetTenantInformation: Parses the federation metadata document and gets issuer Name and Signing Certificates

    Parses the federation metadata document and gets issuer Name and Signing Certificates URL of the Federation Metadata document Issuer Name Signing Certificates in the form of X509SecurityToken
    static DateTime _stsMetadataRetrievalTime = DateTime.MinValue;
    static string _issuer = string.Empty;
    static List<X509SecurityToken> _signingTokens = null;
    
    /// <summary>
    /// Parses the federation metadata document and gets issuer Name and Signing Certificates
    /// </summary>
    /// <param name="metadataAddress">URL of the Federation Metadata document</param>
    /// <param name="issuer">Issuer Name</param>
    /// <param name="signingTokens">Signing Certificates in the form of X509SecurityToken</param>
    static void GetTenantInformation(string metadataAddress, out string issuer, out List<X509SecurityToken> signingTokens)
    {
        signingTokens = new List<X509SecurityToken>();
    
        // The issuer and signingTokens are cached for 24 hours. They are updated if any of the conditions in the if condition is true.            
        if (DateTime.UtcNow.Subtract(_stsMetadataRetrievalTime).TotalHours > 24
            || string.IsNullOrEmpty(_issuer)
            || _signingTokens == null)
        {
            MetadataSerializer serializer = new MetadataSerializer()
            {
                // turning off certificate validation for demo. Don't use this in production code.
                CertificateValidationMode = X509CertificateValidationMode.None
            };
            MetadataBase metadata = serializer.ReadMetadata(XmlReader.Create(metadataAddress));
    
            EntityDescriptor entityDescriptor = (EntityDescriptor)metadata;
    
            // get the issuer name
            if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id))
            {
                _issuer = entityDescriptor.EntityId.Id;
            }
    
            // get the signing certs
            _signingTokens = ReadSigningCertsFromMetadata(entityDescriptor);
    
            _stsMetadataRetrievalTime = DateTime.UtcNow;
        }
    
        issuer = _issuer;
        signingTokens = _signingTokens;
    }

    public by msdn  1642  0  6  0

    GetTenantInformation: Parses the federation metadata document and gets issuer Name and Signing Certificates

    Parses the federation metadata document and gets issuer Name and Signing Certificates URL of the Federation Metadata document Issuer Name Signing Certificates in the form of X509SecurityToken
    using System;
    using System.Collections.Generic;
    using System.IdentityModel.Metadata;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Security.Claims;
    using System.Security.Cryptography.X509Certificates;
    using System.ServiceModel.Security;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using System.Xml;
    using System.Xml.Linq;
    
    static DateTime _stsMetadataRetrievalTime = DateTime.MinValue;
    static string _issuer = string.Empty;
    static List<X509SecurityToken> _signingTokens = null;
    
    /// <summary>
    /// Parses the federation metadata document and gets issuer Name and Signing Certificates
    /// </summary>
    /// <param name="metadataAddress">URL of the Federation Metadata document</param>
    /// <param name="issuer">Issuer Name</param>
    /// <param name="signingTokens">Signing Certificates in the form of X509SecurityToken</param>
    static void GetTenantInformation(string metadataAddress, out string issuer, out List<X509SecurityToken> signingTokens)
    {
        signingTokens = new List<X509SecurityToken>();
    
        // The issuer and signingTokens are cached for 24 hours. They are updated if any of the conditions in the if condition is true.            
        if (DateTime.UtcNow.Subtract(_stsMetadataRetrievalTime).TotalHours > 24
            || string.IsNullOrEmpty(_issuer)
            || _signingTokens == null)
        {
            MetadataSerializer serializer = new MetadataSerializer()
            {
                CertificateValidationMode = X509CertificateValidationMode.None
            };
            MetadataBase metadata = serializer.ReadMetadata(XmlReader.Create(metadataAddress));
    
            EntityDescriptor entityDescriptor = (EntityDescriptor)metadata;
    
            // get the issuer name
            if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id))
            {
                _issuer = entityDescriptor.EntityId.Id;
            }
    
            // get the signing certs
            _signingTokens = ReadSigningCertsFromMetadata(entityDescriptor);
    
            _stsMetadataRetrievalTime = DateTime.UtcNow;
        }
    
        issuer = _issuer;
        signingTokens = _signingTokens;
    }

    public by msdn  1595  0  6  0

    GetTenantInformation: Parses the federation metadata document and gets issuer Name and Signing Certificates

    Parses the federation metadata document and gets issuer Name and Signing Certificates URL of the Federation Metadata document Issuer Name Signing Certificates in the form of X509SecurityToken
    using System;
    using System.Collections.Generic;
    using System.IdentityModel.Metadata;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Security.Claims;
    using System.Security.Cryptography.X509Certificates;
    using System.ServiceModel.Security;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using System.Xml;
    
    static DateTime _stsMetadataRetrievalTime = DateTime.MinValue;
    static string _issuer = string.Empty;
    static List<X509SecurityToken> _signingTokens;
    
    /// <summary>
    /// Parses the federation metadata document and gets issuer Name and Signing Certificates
    /// </summary>
    /// <param name="metadataAddress">URL of the Federation Metadata document</param>
    /// <param name="issuer">Issuer Name</param>
    /// <param name="signingTokens">Signing Certificates in the form of X509SecurityToken</param>
    static void GetTenantInformation(string metadataAddress, out string issuer, out List<X509SecurityToken> signingTokens)
    {
        signingTokens = new List<X509SecurityToken>();
    
        // The issuer and signingTokens are cached for 24 hours. They are updated if any of the conditions in the if condition is true.            
        if (DateTime.UtcNow.Subtract(_stsMetadataRetrievalTime).TotalHours > 24
            || string.IsNullOrEmpty(_issuer)
            || _signingTokens == null)
        {
            MetadataSerializer serializer = new MetadataSerializer()
            {
                // turning off certificate validation for demo. Don't use this in production code.
                CertificateValidationMode = X509CertificateValidationMode.None
            };
            MetadataBase metadata = serializer.ReadMetadata(XmlReader.Create(metadataAddress));
    
            EntityDescriptor entityDescriptor = (EntityDescriptor)metadata;
    
            // get the issuer name
            if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id))
            {
                _issuer = entityDescriptor.EntityId.Id;
            }
    
            // get the signing certs
            _signingTokens = ReadSigningCertsFromMetadata(entityDescriptor);
    
            _stsMetadataRetrievalTime = DateTime.UtcNow;
        }
    
        issuer = _issuer;
        signingTokens = _signingTokens;
    }

    public by msdn  1318  0  6  0

    GetTenantInformation: Parses the federation metadata document and gets issuer Name and Signing Certificates

    Parses the federation metadata document and gets issuer Name and Signing Certificates URL of the Federation Metadata document Issuer Name Signing Certificates in the form of X509SecurityToken
    using System;
    using System.Collections.Generic;
    using System.IdentityModel.Metadata;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Security.Claims;
    using System.Security.Cryptography.X509Certificates;
    using System.ServiceModel.Security;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using System.Xml;
    
    static DateTime _stsMetadataRetrievalTime = DateTime.MinValue;
    static string _issuer = string.Empty;
    static List<X509SecurityToken> _signingTokens = null;
    
    /// <summary>
    /// Parses the federation metadata document and gets issuer Name and Signing Certificates
    /// </summary>
    /// <param name="metadataAddress">URL of the Federation Metadata document</param>
    /// <param name="issuer">Issuer Name</param>
    /// <param name="signingTokens">Signing Certificates in the form of X509SecurityToken</param>
    static void GetTenantInformation(string metadataAddress, out string issuer, out List<X509SecurityToken> signingTokens)
    {
        signingTokens = new List<X509SecurityToken>();
    
        // The issuer and signingTokens are cached for 24 hours. They are updated if any of the conditions in the if condition is true.            
        if (DateTime.UtcNow.Subtract(_stsMetadataRetrievalTime).TotalHours > 24
            || string.IsNullOrEmpty(_issuer)
            || _signingTokens == null)
        {
            MetadataSerializer serializer = new MetadataSerializer()
                {
                    // turning off certificate validation for demo. Don't use this in production code.
                    CertificateValidationMode = X509CertificateValidationMode.None
                };
            MetadataBase metadata = serializer.ReadMetadata(XmlReader.Create(metadataAddress));
    
            EntityDescriptor entityDescriptor = (EntityDescriptor)metadata;
    
            // get the issuer name
            if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id))
            {
                _issuer = entityDescriptor.EntityId.Id;
            }
    
            // get the signing certs
            _signingTokens = ReadSigningCertsFromMetadata(entityDescriptor);
    
            _stsMetadataRetrievalTime = DateTime.UtcNow;
        }
    
        issuer = _issuer;
        signingTokens = _signingTokens;
    }
    • Public Snippets
    • Channels Snippets