public static void TestKnownValues() { Oid oid; oid = Oid.FromFriendlyName(SHA1_Name, OidGroup.All); Assert.Equal(SHA1_Name, oid.FriendlyName); Assert.Equal(SHA1_Oid, oid.Value); oid = Oid.FromFriendlyName(SHA256_Name, OidGroup.All); Assert.Equal(SHA256_Name, oid.FriendlyName); Assert.Equal(SHA256_Oid, oid.Value); // Note that oid lookup is case-insensitive, and we store the name in the form it was input to the constructor (rather than "normalizing" it // to the official casing.) oid = Oid.FromFriendlyName("MD5", OidGroup.All); Assert.Equal("MD5", oid.FriendlyName); Assert.Equal("1.2.840.113549.2.5", oid.Value); oid = Oid.FromFriendlyName("sha384", OidGroup.All); Assert.Equal("sha384", oid.FriendlyName); Assert.Equal("2.16.840.1.101.3.4.2.2", oid.Value); oid = Oid.FromFriendlyName("sha512", OidGroup.All); Assert.Equal("sha512", oid.FriendlyName); Assert.Equal("2.16.840.1.101.3.4.2.3", oid.Value); oid = Oid.FromFriendlyName("3des", OidGroup.All); Assert.Equal("3des", oid.FriendlyName); Assert.Equal("1.2.840.113549.3.7", oid.Value); }
public void testSignSimpleContainerECDsa() { string testFileName = @"..\..\..\resources\circles.pdf"; string storePath = @"..\..\..\..\simple\keystore\test1234.p12"; string storePass = "******"; string storeAlias = "ECDSAkey"; SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection(); pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet); SystemCertificates.X509Certificate2 certificate = null; foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12) { if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase)) { certificate = aCertificate; break; } } Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias); X509Certificate2SignatureContainer signature = new X509Certificate2SignatureContainer(certificate, signer => { signer.DigestAlgorithm = Oid.FromFriendlyName("SHA512", OidGroup.HashAlgorithm); }); using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-ECDSA-signed-simple-container.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); pdfSigner.SignExternalContainer(signature, 8192); } }
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes to search Oid in the lookup table public static void LookupOidByFriendlyName_Method_UnixOnly() { // This needs to be a name not in the static lookup table. The purpose is to verify the // NativeFriendlyNameToOid fallback for Unix. For Windows this is accomplished by // using FromOidValue with an OidGroup other than OidGroup.All. Oid oid; try { oid = Oid.FromFriendlyName(ObsoleteSmime3desWrap_Name, OidGroup.All); } catch (CryptographicException) { bool isMac = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); Assert.True(isMac, "Exception is only raised on macOS"); if (isMac) { return; } else { throw; } } Assert.Equal(ObsoleteSmime3desWrap_Oid, oid.Value); Assert.Equal(ObsoleteSmime3desWrap_Name, oid.FriendlyName); }
public static void LookupOidByFriendlyName_AdditionalNames(string friendlyName, string expectedOid) { Oid oid = Oid.FromFriendlyName(friendlyName, OidGroup.All); Assert.Equal(friendlyName, oid.FriendlyName); Assert.Equal(expectedOid, oid.Value); }
public static void LookupOidByFriendlyName_Method_EncryptionAlgorithm(string oidValue, string friendlyName) { Oid oid = Oid.FromFriendlyName(friendlyName, OidGroup.EncryptionAlgorithm); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); }
private CX509CertificateRequestCertificate FinalizeRequest(CX509CertificateRequestCertificate cert) { var subDN = new CX500DistinguishedName(); subDN.Encode("CN=" + SubjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); cert.Subject = subDN; cert.Issuer = cert.Subject; cert.NotBefore = DateTime.Now; cert.NotAfter = ValidUntil; for (int i = 0; i < ExtensionsToAdd.Count; i++) { var ext = ExtensionsToAdd[i]; cert.X509Extensions.Add(ext); } var sigId = new CObjectId(); var hash = Oid.FromFriendlyName(Algorithm, OidGroup.HashAlgorithm); sigId.InitializeFromValue(hash.Value); cert.SignatureInformation.HashAlgorithm = sigId; // Complete it cert.Encode(); ExtensionsToAdd.Clear(); return(cert); }
public static AsnOid FromFriendlyName(string name) { AsnOid val = null; try { val = new AsnOid(Oid.FromFriendlyName(name, OidGroup.All)); } catch { } if (val == null) { switch (name) { case "X509v3 Key Usage": val = new AsnOid(new Oid("2.5.29.15")); break; case "X509v3 Subject Key Identifier": val = new AsnOid(Oid.FromFriendlyName("Subject Key Identifier", OidGroup.All)); break; } } return(val); }
public void WriteObjectIdentifier_CustomTag_Oid(PublicEncodingRules ruleSet) { AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet); writer.WriteObjectIdentifier(new Asn1Tag(TagClass.Private, 36), Oid.FromFriendlyName("SHA1", OidGroup.HashAlgorithm)); Verify(writer, "DF24052B0E03021A"); }
public static void LookupOidByFriendlyName_Method_UnixOnly() { // This needs to be a name not in the static lookup table. The purpose is to verify the // NativeFriendlyNameToOid fallback for Unix. For Windows this is accomplished by // using FromOidValue with an OidGroup other than OidGroup.All. Oid oid = Oid.FromFriendlyName(ObsoleteSmime3desWrap_Name, OidGroup.All); Assert.Equal(ObsoleteSmime3desWrap_Oid, oid.Value); Assert.Equal(ObsoleteSmime3desWrap_Name, oid.FriendlyName); }
public static void LookupOidByFriendlyName_Method_InverseCase(string oidValue, string friendlyName) { // Note that oid lookup is case-insensitive, and we store the name in the form it was // input to the constructor (rather than "normalizing" it to the official casing.) string inverseCasedName = InvertCase(friendlyName); Oid oid = Oid.FromFriendlyName(inverseCasedName, OidGroup.All); Assert.Equal(oidValue, oid.Value); Assert.Equal(inverseCasedName, oid.FriendlyName); }
private void SetEnhancedUsages() { var oids = new CObjectIds(); for (int i = 0; i < EnhancedUsages.Length; i++) { var s = EnhancedUsages[i]; var oid = new CObjectId(); var eu = Oid.FromFriendlyName(s, OidGroup.EnhancedKeyUsage); oid.InitializeFromValue(eu.Value); } var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oids); ExtensionsToAdd.Add((CX509Extension)eku); }
/// <summary> /// Signs a payload, using CMS, with the provided certificate /// </summary> /// <param name="payload">The bytes to sign</param> /// <param name="signingCertificate">The certificate to sign with</param> /// <returns>The signature</returns> private static byte[] SignBytes(byte[] payload, X509Certificate2 signingCertificate) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate) { IncludeOption = X509IncludeOption.WholeChain, DigestAlgorithm = Oid.FromFriendlyName(RdpSignatureDigestAlgorithmName, OidGroup.All) }; ContentInfo content = new ContentInfo(payload); SignedCms cmsPayload = new SignedCms(content, true); cmsPayload.ComputeSignature(signer); return(cmsPayload.Encode()); }
protected override void LoadConfiguration(XmlReader configuration) { /* * <xsd:element minOccurs="1" name="URL" type="xsd:string" /> * <xsd:element minOccurs="1" name="ValidateCertificate" type="xsd:boolean" /> * <xsd:element minOccurs="1" name="DisabledHash" type="xsd:string" /> * <xsd:element minOccurs="0" name="DNSServerList" type="xsd:string" /> * <xsd:element minOccurs="0" name="DNSRequestTimeoutSec" type="xsd:integer" /> */ try { var xmlDoc = new XmlDocument(); xmlDoc.Load(configuration); LoadConfigurationElement(xmlDoc, "URL", out string strURL); LoadConfigurationElement(xmlDoc, "DisabledHash", out string strDisabledHash); LoadConfigurationElement(xmlDoc, "ValidateCertificate", out _validateCertificate); LoadConfigurationElement(xmlDoc, "DNSServerList", out string strDNSServerList, null, false); LoadConfigurationElement(xmlDoc, "DNSRequestTimeoutSec", out _dnsRequestTimeout, 20, false); // Convert to hash list _disabledHashes = new List <Oid>(); foreach (string hashName in strDisabledHash.Split(TcpHelper.Separators, StringSplitOptions.RemoveEmptyEntries)) { _disabledHashes.Add(Oid.FromFriendlyName(hashName, OidGroup.SignatureAlgorithm)); } // parse URL _testUri = new Uri(strURL); // parse DNS _dnsRequestTimeout *= 1000; _customDnsServers = new List <IPAddress>(); if (!string.IsNullOrWhiteSpace(strDNSServerList)) { foreach (string dnsIPstr in strDNSServerList.Split(TcpHelper.Separators, StringSplitOptions.RemoveEmptyEntries)) { _customDnsServers.Add(IPAddress.Parse(dnsIPstr.Trim())); } } } catch (Exception ex) { throw new ModuleException("Error parsing configuration XML", ex); } }
public static void TestFromFriendlyName() { Oid oid; oid = Oid.FromFriendlyName(SHA1_Name, OidGroup.HashAlgorithm); Assert.Equal(SHA1_Name, oid.FriendlyName); Assert.Equal(SHA1_Oid, oid.Value); oid = Oid.FromFriendlyName(SHA256_Name, OidGroup.HashAlgorithm); Assert.Equal(SHA256_Name, oid.FriendlyName); Assert.Equal(SHA256_Oid, oid.Value); Assert.Throws <ArgumentNullException>(() => Oid.FromFriendlyName(null, OidGroup.HashAlgorithm)); Assert.Throws <CryptographicException>(() => Oid.FromFriendlyName(Bogus_Name, OidGroup.HashAlgorithm)); // Oid group is implemented strictly - no fallback to OidGroup.All as with many other parts of Crypto. Assert.Throws <CryptographicException>(() => Oid.FromFriendlyName(SHA1_Name, OidGroup.Policy)); }
private static bool NativeOidFriendlyNameExists(string oidFriendlyName) { if (string.IsNullOrEmpty(oidFriendlyName)) { return(false); } try { // By specifying OidGroup.PublicKeyAlgorithm, no caches are used // Note: this throws when there is no oid value, even when friendly name is valid // so it cannot be used for curves with no oid value such as curve25519 return(!string.IsNullOrEmpty(Oid.FromFriendlyName(oidFriendlyName, OidGroup.PublicKeyAlgorithm).FriendlyName)); } catch (Exception) { return(false); } }
private CX509CertificateRequestCertificate CreateRequest(KeyLengths keyLength) { var pk = new CX509PrivateKey { ProviderName = provName }; var algId = new CObjectId(); var algVal = Oid.FromFriendlyName("RSA", OidGroup.PublicKeyAlgorithm); algId.InitializeFromValue(algVal.Value); pk.Algorithm = algId; pk.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; // If this value is anything other KEYEXCHANGE, the certificate cannot be used for decrypting content. pk.Length = (int)keyLength; pk.MachineContext = true; pk.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE; pk.Create(); var req = new CX509CertificateRequestCertificate(); var useCtx = (X509CertificateEnrollmentContext)StoreLocation.LocalMachine; req.InitializeFromPrivateKey(useCtx, pk, string.Empty); return(req); }
private CX509CertificateRequestCertificate CreateRequest() { var pk = new CX509PrivateKey { ProviderName = provName }; var algId = new CObjectId(); var algVal = Oid.FromFriendlyName("RSA", OidGroup.PublicKeyAlgorithm); algId.InitializeFromValue(algVal.Value); pk.Algorithm = algId; pk.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; pk.Length = KeyLength; pk.MachineContext = MachineContext; pk.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; pk.Create(); var req = new CX509CertificateRequestCertificate(); var useCtx = (X509CertificateEnrollmentContext)Store; req.InitializeFromPrivateKey(useCtx, pk, string.Empty); return(req); }
public SimpleCA(string countryCode, string organization, string orgunit, string commonName) { var distinguishedName = $"C={countryCode};O={organization};OU={orgunit};CN={commonName}"; //var distinguishedName = "C=US;O=Microsoft;OU=WGA;CN=TedSt"; //CN={commonName}/OU={organizationUnit}/O={organization}/DC={domain}/STREET={address}/L={locality}/ST={state}/C={country}/DC={domainComponent}" var dn = new System.Security.Cryptography.X509Certificates.X500DistinguishedName( distinguishedName ); var key = System.Security.Cryptography.RSA.Create(); key.KeySize = 4096; var hash = System.Security.Cryptography.HashAlgorithmName.SHA512; var req = new System.Security.Cryptography.X509Certificates.CertificateRequest(dn, key, hash, RSASignaturePadding.Pss); var q = Oid.FromFriendlyName("", OidGroup.EnhancedKeyUsage); Oid.FromOidValue("", OidGroup.EnhancedKeyUsage); var r = new OidCollection(); r.Add(q); var v = new X509EnhancedKeyUsageExtension(r, false); req.CertificateExtensions.Add(SetEnhancedKeyUsage(keyCertSign: true)); req.CertificateExtensions.Add(SetBasicConstraints(true)); req.CertificateExtensions.Add(v); var now = DateTimeOffset.UtcNow; var startDate = now - TimeSpan.FromMinutes(5); var endDate = DateTimeOffset.UtcNow + TimeSpan.FromDays(365.25 * 10); rootCert = req.CreateSelfSigned(startDate, endDate); rootKey = key; var rootKeyChain = rootCert.Export(X509ContentType.Pkcs12); }
public static Oid GetOID(this HashProvider ForProvider) { return(Oid.FromFriendlyName(ForProvider.ToString(), OidGroup.HashAlgorithm)); }
public static void LookupOidByFriendlyName_Method_BadInput(string badInput) { Assert.Throws <CryptographicException>(() => Oid.FromFriendlyName(badInput, OidGroup.HashAlgorithm)); }
public static void LookupOidByFriendlyName_Method_NullInput() { Assert.Throws <ArgumentNullException>(() => Oid.FromFriendlyName(null, OidGroup.HashAlgorithm)); }
public static void LookupOidByFriendlyName_Method_WrongGroup(string oidValue, string friendlyName) { // Oid group is implemented strictly - no fallback to OidGroup.All as with many other parts of Crypto. Assert.Throws <CryptographicException>(() => Oid.FromFriendlyName(friendlyName, OidGroup.EncryptionAlgorithm)); }
public override void SetHashAlgorithm(string strName) { // Verify the name Oid.FromFriendlyName(strName, OidGroup.HashAlgorithm); this.HashAlgorithmName = strName; }
/// <summary> /// Converts DistinguishedNames to X509Name /// </summary> /// <param name="dn">Distinguished names that were filled by user</param> /// <returns>X509Name to be used in certificate builder</returns> private X509Name DistinguishedNamesToX509Name(DistinguishedNames dn) { StringBuilder builder = new StringBuilder(); if (dn.otherDN != null && dn.otherDN.Count > 0) { foreach (string key in dn.otherDN.Keys) { builder.Append(Oid.FromFriendlyName(key, OidGroup.All).Value).Append("=").Append(dn.otherDN[key]).Append(","); } } if (dn.domainComponent != null && dn.domainComponent.Length > 0) { foreach (string dc in dn.domainComponent) { builder.Append("0.9.2342.19200300.100.1.25=").Append(dc).Append(","); } } if (dn.countryName != null && dn.countryName.Length > 0) { builder.Append("2.5.4.6=").Append(dn.countryName).Append(","); } if (dn.stateOrProvinceName != null && dn.stateOrProvinceName.Length > 0) { builder.Append("2.5.4.8=").Append(dn.stateOrProvinceName).Append(","); } if (dn.localityName != null && dn.localityName.Length > 0) { builder.Append("2.5.4.7=").Append(dn.localityName).Append(","); } if (dn.streetAddress != null && dn.streetAddress.Length > 0) { builder.Append("2.5.4.9=").Append(dn.streetAddress).Append(","); } if (dn.organizationName != null && dn.organizationName.Length > 0) { builder.Append("2.5.4.10=").Append(dn.organizationName).Append(","); } if (dn.organizationalUnitName != null && dn.organizationalUnitName.Length > 0) { builder.Append("2.5.4.11=").Append(dn.organizationalUnitName).Append(","); } if (dn.emailAddress != null && dn.emailAddress.Length > 0) { builder.Append("1.2.840.113549.1.9.1=").Append(dn.emailAddress).Append(","); } if (dn.userId != null && dn.userId.Length > 0) { builder.Append("0.9.2342.19200300.100.1.1=").Append(dn.userId).Append(","); } if (dn.commonName != null && dn.commonName.Length > 0) { builder.Append("2.5.4.3=").Append(dn.commonName).Append(","); } //Remove the last coma if (builder.Length > 0) { builder.Remove(builder.Length - 1, 1); } return(new X509Name(builder.ToString())); }
protected override void LoadConfiguration(XmlDocument cfgDoc) { try { // base class properties LoadConfigurationElement(cfgDoc, "TestDisplayName", out TestDisplayName, "<no test name provided>", false); // for logging purposes only // parent class property LoadConfigurationElement(cfgDoc, "FullyQualifiedDomainName", out FullyQualifiedDomainName); LoadConfigurationElement(cfgDoc, "TargetIndex", out TargetIndex); // specific class properties LoadConfigurationElement(cfgDoc, "Schema", out Schema, null, false); LoadConfigurationElement(cfgDoc, "Port", out Port, -1, false); LoadConfigurationElement(cfgDoc, "IgnoreRevocationCheck", out IgnoreRevocationCheck, false, false); LoadConfigurationElement(cfgDoc, "ApplicationPolicy", out string strApplicationPolicy, "", false); LoadConfigurationElement(cfgDoc, "CertificatePolicy", out string strCertificatePolicy, "", false); LoadConfigurationElement(cfgDoc, "DisabledHash", out string strDisabledHash, "", false); LoadConfigurationElement(cfgDoc, "AllowedSSLProtocols", out string strAllowedSSLProtocols, "", false); LoadConfigurationElement(cfgDoc, "DisabledSSLProtocols", out string strDisabledSSLProtocols, "", false); LoadConfigurationElement(cfgDoc, "AllowUnknownCertificateAuthority", out AllowUnknownCertificateAuthority, false, false); LoadConfigurationElement(cfgDoc, "IgnoreCertificateAuthorityRevocationUnknown", out IgnoreCertificateAuthorityRevocationUnknown, false, false); LoadConfigurationElement(cfgDoc, "IgnoreCtlNotTimeValid", out IgnoreCtlNotTimeValid, false, false); LoadConfigurationElement(cfgDoc, "IgnoreCtlSignerRevocationUnknown", out IgnoreCtlSignerRevocationUnknown, false, false); LoadConfigurationElement(cfgDoc, "IgnoreEndRevocationUnknown", out IgnoreEndRevocationUnknown, false, false); LoadConfigurationElement(cfgDoc, "IgnoreInvalidBasicConstraints", out IgnoreInvalidBasicConstraints, false, false); LoadConfigurationElement(cfgDoc, "IgnoreInvalidName", out IgnoreInvalidName, false, false); LoadConfigurationElement(cfgDoc, "IgnoreInvalidPolicy", out IgnoreNotTimeNested, false, false); LoadConfigurationElement(cfgDoc, "IgnoreNotTimeValid", out IgnoreNotTimeValid, false, false); LoadConfigurationElement(cfgDoc, "IgnoreRootRevocationUnknown", out IgnoreRootRevocationUnknown, false, false); LoadConfigurationElement(cfgDoc, "IgnoreWrongUsage", out IgnoreWrongUsage, false, false); // parse ApplicationPolicy = new List <Oid>(); if (!string.IsNullOrWhiteSpace(strApplicationPolicy)) { foreach (string strOid in strApplicationPolicy.Split(ModInit.Separators, StringSplitOptions.RemoveEmptyEntries)) { try { ApplicationPolicy.Add(new Oid(strOid.Trim())); } catch (Exception e) { ModInit.Logger.WriteWarning($"Error while parsing OID list for Application Policy. Value {strOid} is not recognized as a valid OID. OID was skipped.\r\nError message: {e.Message}", this); } } } CertificatePolicy = new List <Oid>(); if (!string.IsNullOrWhiteSpace(strCertificatePolicy)) { foreach (string strOid in strCertificatePolicy.Split(ModInit.Separators, StringSplitOptions.RemoveEmptyEntries)) { try { CertificatePolicy.Add(new Oid(strOid.Trim())); } catch (Exception e) { ModInit.Logger.WriteWarning($"Error while parsing OID list for Certificate Policy. Value {strOid} is not recognized as a valid OID. OID was skipped.\r\nError message: {e.Message}", this); } } } DisabledHash = new List <Oid>(); foreach (string hashName in strDisabledHash.Split(ModInit.Separators, StringSplitOptions.RemoveEmptyEntries)) { DisabledHash.Add(Oid.FromFriendlyName(hashName.Trim(), OidGroup.SignatureAlgorithm)); } AllowedSSLProtocols = new List <SslProtocols>(); if (!string.IsNullOrWhiteSpace(strAllowedSSLProtocols)) { foreach (string sslProtoName in strAllowedSSLProtocols.Split(ModInit.Separators, StringSplitOptions.RemoveEmptyEntries)) { if (Enum.TryParse(sslProtoName, true, out SslProtocols protocol)) { AllowedSSLProtocols.Add(protocol); } else { ModInit.Logger.WriteWarning($"Error while parsing SSL Protocols list for Allowed SSL Protocols. Value {sslProtoName} is not recognized as a valid SSL protocol name. Value was skipped.", this); } } } DisabledSSLProtocols = new List <SslProtocols>(); if (!string.IsNullOrWhiteSpace(strDisabledSSLProtocols)) { foreach (string sslProtoName in strDisabledSSLProtocols.Split(ModInit.Separators, StringSplitOptions.RemoveEmptyEntries)) { if (Enum.TryParse(sslProtoName, true, out SslProtocols protocol)) { DisabledSSLProtocols.Add(protocol); } else { ModInit.Logger.WriteWarning($"Error while parsing SSL Protocols list for Disabled SSL Protocols. Value {sslProtoName} is not recognized as a valid SSL protocol name. Value was skipped.", this); } } } } catch (Exception e) { ModuleErrorSignalReceiver(ModuleErrorSeverity.FatalError, ModuleErrorCriticality.Stop, e, "Failed to load module configuration."); throw new ModuleException("Failed to load module configuration.", e); } }