/// <inheritdoc /> public IAsymmetricKeyAlgorithmProvider OpenAlgorithm(AsymmetricAlgorithm algorithm) { switch (algorithm) { #if DESKTOP case AsymmetricAlgorithm.DsaSha1: case AsymmetricAlgorithm.DsaSha256: case AsymmetricAlgorithm.EcdsaP256Sha256: case AsymmetricAlgorithm.EcdsaP384Sha384: case AsymmetricAlgorithm.EcdsaP521Sha512: return new CngAsymmetricKeyAlgorithmProvider(algorithm); #endif #if !SILVERLIGHT || WINDOWS_PHONE case AsymmetricAlgorithm.RsaOaepSha1: case AsymmetricAlgorithm.RsaOaepSha256: case AsymmetricAlgorithm.RsaOaepSha384: case AsymmetricAlgorithm.RsaOaepSha512: case AsymmetricAlgorithm.RsaPkcs1: case AsymmetricAlgorithm.RsaSignPkcs1Sha1: case AsymmetricAlgorithm.RsaSignPkcs1Sha256: case AsymmetricAlgorithm.RsaSignPkcs1Sha384: case AsymmetricAlgorithm.RsaSignPkcs1Sha512: case AsymmetricAlgorithm.RsaSignPssSha1: case AsymmetricAlgorithm.RsaSignPssSha256: case AsymmetricAlgorithm.RsaSignPssSha384: case AsymmetricAlgorithm.RsaSignPssSha512: return new RsaAsymmetricKeyAlgorithmProvider(algorithm); #endif default: throw new NotSupportedException(); } }
/// <summary> /// Gets the hash algorithm for a given asymmetric algorithm. /// </summary> /// <param name="algorithm">The algorithm.</param> /// <returns>A hash algorithm.</returns> internal static HashAlgorithm GetHashAlgorithmEnum(AsymmetricAlgorithm algorithm) { switch (algorithm) { case AsymmetricAlgorithm.DsaSha1: case AsymmetricAlgorithm.RsaOaepSha1: case AsymmetricAlgorithm.RsaSignPkcs1Sha1: case AsymmetricAlgorithm.RsaSignPssSha1: return HashAlgorithm.Sha1; case AsymmetricAlgorithm.DsaSha256: case AsymmetricAlgorithm.RsaOaepSha256: case AsymmetricAlgorithm.EcdsaP256Sha256: case AsymmetricAlgorithm.RsaSignPkcs1Sha256: case AsymmetricAlgorithm.RsaSignPssSha256: return HashAlgorithm.Sha256; case AsymmetricAlgorithm.EcdsaP384Sha384: case AsymmetricAlgorithm.RsaOaepSha384: case AsymmetricAlgorithm.RsaSignPkcs1Sha384: case AsymmetricAlgorithm.RsaSignPssSha384: return HashAlgorithm.Sha384; case AsymmetricAlgorithm.EcdsaP521Sha512: case AsymmetricAlgorithm.RsaOaepSha512: case AsymmetricAlgorithm.RsaSignPkcs1Sha512: case AsymmetricAlgorithm.RsaSignPssSha512: return HashAlgorithm.Sha512; default: throw new NotSupportedException(); } }
public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; }
public override void SetKey(AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; }
internal PublicKey (Mono.Security.X509.X509Certificate certificate) { if (certificate.KeyAlgorithm == "1.2.840.113549.1.1.1") { _key = certificate.RSA; } else { _key = certificate.DSA; } _oid = new Oid (certificate.KeyAlgorithm); _keyValue = new AsnEncodedData (_oid, certificate.PublicKey); _params = new AsnEncodedData (_oid, certificate.KeyAlgorithmParameters); }
public override void Reset() { _lazyRawData = null; _lazySignatureAlgorithm = null; _lazyVersion = 0; _lazySubjectName = null; _lazyIssuerName = null; _lazyPublicKey = null; _lazyPrivateKey = null; _lazyExtensions = null; base.Reset(); }
internal PublicKey (MSX.X509Certificate certificate) { // note: _key MUSTonly contains the public part of the key bool export_required = true; if (certificate.KeyAlgorithm == rsaOid) { #if !MOONLIGHT // shortcut export/import in the case the private key isn't available RSACryptoServiceProvider rcsp = (certificate.RSA as RSACryptoServiceProvider); if ((rcsp != null) && rcsp.PublicOnly) { _key = certificate.RSA; export_required = false; } else #endif { RSAManaged rsam = (certificate.RSA as RSAManaged); if ((rsam != null) && rsam.PublicOnly) { _key = certificate.RSA; export_required = false; } } if (export_required) { RSAParameters rsap = certificate.RSA.ExportParameters (false); _key = RSA.Create (); (_key as RSA).ImportParameters (rsap); } } else { #if !MOONLIGHT // shortcut export/import in the case the private key isn't available DSACryptoServiceProvider dcsp = (certificate.DSA as DSACryptoServiceProvider); if ((dcsp != null) && dcsp.PublicOnly) { _key = certificate.DSA; export_required = false; } // note: DSAManaged isn't available in Mono.Security due to a bug in Fx 1.x if (export_required) { DSAParameters rsap = certificate.DSA.ExportParameters (false); _key = DSA.Create (); (_key as DSA).ImportParameters (rsap); } #endif } _oid = new Oid (certificate.KeyAlgorithm); _keyValue = new AsnEncodedData (_oid, certificate.PublicKey); _params = new AsnEncodedData (_oid, certificate.KeyAlgorithmParameters); }
public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key) { this.sock = sock; this.epl = epl; this.secure = secure; this.key = key; if (secure == false) { stream = new NetworkStream (sock, false); } else { SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, true, false); ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection; ssl_stream.ClientCertValidationDelegate += OnClientCertificateValidation; stream = ssl_stream; } timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite); Init (); }
public void LegalKeySizes(AsymmetricAlgorithm name, int minSize, int maxSize, int stepSize) { IAsymmetricKeyAlgorithmProvider provider = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(name); var result = provider.LegalKeySizes; Assert.NotNull(result); Assert.NotEmpty(result); Action<int> attemptKeySize = size => { provider.CreateKeyPair(size).Dispose(); }; var range = result.Single(); Assert.Equal(minSize, range.MinSize); Assert.Equal(maxSize, range.MaxSize); Assert.Equal(stepSize, range.StepSize); }
public void AsymmetricEncryption(AsymmetricAlgorithm algorithmName) { var algorithm = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName); foreach (var keySize in algorithm.LegalKeySizes.SelectMany(k => k)) { try { this.logger.WriteLine($"Testing {algorithmName} with {keySize} bit key."); using (var key = algorithm.CreateKeyPair(keySize)) { } break; } catch (ArgumentException) { // WinRT does not provide legal key sizes, and doesn't allow small RSA keys. // It throws ArgumentException in this case. We can remove the skip on ArgumentException // after we switch WinRT over to using BCrypt directly. this.logger.WriteLine("Key size rejected. Please fix LegalKeySizes to report key sizes that actually work."); } } }
public void ToCapiKeyBlob_AsymmetricNull() { AsymmetricAlgorithm aa = null; CryptoConvert.ToCapiKeyBlob(aa, false); }
protected RSAPKCS1Algorithm(string hashAlgorithm, AsymmetricAlgorithm publicKey = null, AsymmetricAlgorithm privateKey = null) : this(hashAlgorithm) { if (publicKey.KeySize < 2048) { throw new ArgumentException("Key size must be at 2048bits"); } if (privateKey.KeySize < 2048) { throw new ArgumentException("Key size must be at 2048bits"); } this.disposePublicKey = false; this.disposePrivateKey = false; this.publicKey = publicKey; this.privateKey = privateKey; }
public override ISignatureTransform CreateSignatureTransform(AsymmetricAlgorithm key) { return(new Rs256SignatureTransform(key)); }
public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) { signingKey = CheckSignatureInternal(null); return(signingKey != null); }
void LoadCertificateAndKey (IPAddress addr, int port) { // Actually load the certificate try { string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); string path = Path.Combine (dirname, ".mono"); path = Path.Combine (path, "httplistener"); string cert_file = Path.Combine (path, String.Format ("{0}.cer", port)); if (!File.Exists (cert_file)) return; string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port)); if (!File.Exists (pvk_file)) return; cert = new X509Certificate2 (cert_file); key = PrivateKey.CreateFromFile (pvk_file).RSA; } catch { // ignore errors } }
/// <summary> /// Initializes a new instance of the <see cref="AsymmetricKeyAlgorithmProvider"/> class. /// </summary> /// <param name="algorithm">The algorithm.</param> public AsymmetricKeyAlgorithmProvider(AsymmetricAlgorithm algorithm) { this.algorithm = algorithm; this.platform = Platform.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(GetAlgorithmName(algorithm)); }
public abstract bool Verify(byte[] hash, AsymmetricAlgorithm key);
/// <inheritdoc /> public Gost_R3410_2012_512_KeyExchangeFormatter(AsymmetricAlgorithm publicKey) : base(publicKey) { }
public PrecheckoutDataService(Environments.Environment environment, string consumerKey, AsymmetricAlgorithm privateKey, String walletUrl) : base(consumerKey, privateKey) { this.environment = environment; this.walletUrl = walletUrl; }
private static void ReplacePublicKeyToken(XmlDocument manifestDom, AsymmetricAlgorithm snKey, bool useSha256) { // Make sure we can find the publicKeyToken attribute. XmlNamespaceManager nsm = new XmlNamespaceManager(manifestDom.NameTable); nsm.AddNamespace("asm", AssemblyNamespaceUri); XmlElement assemblyIdentity = manifestDom.SelectSingleNode("asm:assembly/asm:assemblyIdentity", nsm) as XmlElement; if (assemblyIdentity == null) { throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN); } if (!assemblyIdentity.HasAttribute("publicKeyToken")) { throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN); } byte[] cspPublicKeyBlob; if (snKey is RSACryptoServiceProvider) { cspPublicKeyBlob = (GetFixedRSACryptoServiceProvider((RSACryptoServiceProvider)snKey, useSha256)).ExportCspBlob(false); if (cspPublicKeyBlob == null || cspPublicKeyBlob.Length == 0) { throw new CryptographicException(Win32.NTE_BAD_KEY); } } else { using (RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider()) { rsaCsp.ImportParameters(((RSA)snKey).ExportParameters(false)); cspPublicKeyBlob = rsaCsp.ExportCspBlob(false); } } // Now compute the public key token. unsafe { fixed(byte *pbPublicKeyBlob = cspPublicKeyBlob) { Win32.CRYPT_DATA_BLOB publicKeyBlob = new Win32.CRYPT_DATA_BLOB(); publicKeyBlob.cbData = (uint)cspPublicKeyBlob.Length; publicKeyBlob.pbData = new IntPtr(pbPublicKeyBlob); IntPtr pPublicKeyToken = new IntPtr(); int hr = Win32._AxlPublicKeyBlobToPublicKeyToken(ref publicKeyBlob, ref pPublicKeyToken); if (hr != Win32.S_OK) { throw new CryptographicException(hr); } string publicKeyToken = Marshal.PtrToStringUni(pPublicKeyToken); Win32.HeapFree(Win32.GetProcessHeap(), 0, pPublicKeyToken); assemblyIdentity.SetAttribute("publicKeyToken", publicKeyToken); } } }
internal CmiManifestSigner2(AsymmetricAlgorithm strongNameKey) : this(strongNameKey, null, false) { }
internal override bool Verify(CoseMessage msg, AsymmetricAlgorithm key, byte[] content, byte[]?associatedData = null) { Assert.True(!OnlySupportsDetachedContent || msg.Content == null); return(Sign1Verify(msg, key, content, associatedData)); }
public virtual AsymmetricAlgorithm Convert(AsymmetricAlgorithm privateKey) => null;
public ShippingAddressVerificationService(Environments.Environment environment, string consumerKey, AsymmetricAlgorithm privateKey) : base(consumerKey, privateKey) { this.environment = environment; }
/// <summary> /// Verifies the asymmetric signature of some data blob. /// </summary> /// <param name="signingPublicKey">The public key used to verify the signature.</param> /// <param name="data">The data that was signed.</param> /// <param name="signature">The signature.</param> /// <param name="signingAlgorithm">The signing algorithm.</param> /// <returns> /// A value indicating whether the signature is valid. /// </returns> internal static bool VerifySignatureWithTolerantHashAlgorithm(byte[] signingPublicKey, byte[] data, byte[] signature, AsymmetricAlgorithm? signingAlgorithm = null) { if (signingAlgorithm.HasValue) { var key = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(signingAlgorithm.Value) .ImportPublicKey(signingPublicKey, CryptoSettings.PublicKeyFormat); return WinRTCrypto.CryptographicEngine.VerifySignature(key, data, signature); } var key1 = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaSignPkcs1Sha1) .ImportPublicKey(signingPublicKey, CryptoSettings.PublicKeyFormat); var key2 = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaSignPkcs1Sha256) .ImportPublicKey(signingPublicKey, CryptoSettings.PublicKeyFormat); return WinRTCrypto.CryptographicEngine.VerifySignature(key1, data, signature) || WinRTCrypto.CryptographicEngine.VerifySignature(key2, data, signature); }
public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key) { this.sock = sock; this.epl = epl; this.secure = secure; this.key = key; if (secure == false) { stream = new NetworkStream(sock, false); } else { SslServerStream ssl_stream = new SslServerStream(new NetworkStream(sock, false), cert, false, true, false); ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection; ssl_stream.ClientCertValidationDelegate += OnClientCertificateValidation; stream = ssl_stream; } timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite); Init(); }
public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key) { }
public virtual AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key) { }
// Constructor with the public key to use for encryption. //<Snippet2> public ContosoDeformatter(AsymmetricAlgorithm key) { SetKey(key); }
/// <summary> /// Initializes a new instance of the <see cref="RsaCryptographicKey" /> class. /// </summary> /// <param name="publicKey">The public key.</param> /// <param name="privateKey">The private key.</param> /// <param name="keyIdentifier">The key identifier that may be used to query the keychain.</param> /// <param name="algorithm">The algorithm.</param> internal RsaCryptographicKey(SecKey publicKey, SecKey privateKey, string keyIdentifier, AsymmetricAlgorithm algorithm) { Requires.NotNull(publicKey, "publicKey"); Requires.NotNull(privateKey, "privateKey"); this.publicKey = publicKey; this.privateKey = privateKey; this.keyIdentifier = keyIdentifier; this.algorithm = algorithm; }
private AsymmetricAlgorithm CheckSignatureInternal(AsymmetricAlgorithm key) { pkEnumerator = null; if (key != null) { // check with supplied key if (!CheckSignatureWithKey(key)) { return(null); } } else { #if NET_2_0 if (Signature.KeyInfo == null) { return(null); } #else if (Signature.KeyInfo == null) { throw new CryptographicException("At least one KeyInfo is required."); } #endif // no supplied key, iterates all KeyInfo while ((key = GetPublicKey()) != null) { if (CheckSignatureWithKey(key)) { break; } } pkEnumerator = null; if (key == null) { return(null); } } // some parts may need to be downloaded // so where doing it last if (!CheckReferenceIntegrity(m_signature.SignedInfo.References)) { return(null); } if (manifests != null) { // do not use foreach as a manifest could contain manifests... for (int i = 0; i < manifests.Count; i++) { Manifest manifest = new Manifest((manifests [i] as XmlDocument).DocumentElement); if (!CheckReferenceIntegrity(manifest.References)) { return(null); } } } return(key); }
public RSAPKCS1KeyExchangeFormatter(AsymmetricAlgorithm key) { }
/// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using an /// asymmetric key /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">key being used to verify the signed info</param> /// <param name="signatureDescription">type of signature description class used</param> /// <param name="hashAlgorithm">type of hash algorithm used</param> /// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, AsymmetricAlgorithm key, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerifySignedInfoAsymmetric"), GetKeyName(key), signatureDescription.GetType().Name, hashAlgorithm.GetType().Name, asymmetricSignatureDeformatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_ActualHashValue"), FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RawSignatureValue"), FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } }
public abstract void SetKey(AsymmetricAlgorithm key);
public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key !!) {
public unsafe sealed override ContentInfo TryDecrypt( RecipientInfo recipientInfo, X509Certificate2 cert, AsymmetricAlgorithm privateKey, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception) { Debug.Assert((cert != null) ^ (privateKey != null)); if (privateKey != null) { RSA key = privateKey as RSA; if (key == null) { exception = new CryptographicException(SR.Cryptography_Cms_Ktri_RSARequired); return(null); } ContentInfo contentInfo = _hCryptMsg.GetContentInfo(); byte[] cek = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore( cert, key, recipientInfo.EncryptedKey, recipientInfo.KeyEncryptionAlgorithm.Oid.Value, recipientInfo.KeyEncryptionAlgorithm.Parameters, out exception); // Pin CEK to prevent it from getting copied during heap compaction. fixed(byte *pinnedCek = cek) { try { if (exception != null) { return(null); } return(AnyOS.ManagedPkcsPal.ManagedDecryptorPal.TryDecryptCore( cek, contentInfo.ContentType.Value, contentInfo.Content, _contentEncryptionAlgorithm, out exception)); } finally { if (cek != null) { Array.Clear(cek, 0, cek.Length); } } } } Debug.Assert(recipientInfo != null); Debug.Assert(cert != null); Debug.Assert(originatorCerts != null); Debug.Assert(extraStore != null); CryptKeySpec keySpec; exception = TryGetKeySpecForCertificate(cert, out keySpec); if (exception != null) { return(null); } // Desktop compat: We pass false for "silent" here (thus allowing crypto providers to display UI.) const bool Silent = false; // Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG // because wrapping an NCrypt wrapper over CAPI keys unconditionally causes some legacy features // (such as RC4 support) to break. const bool PreferNCrypt = false; using (SafeProvOrNCryptKeyHandle hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception)) { if (hKey == null) { return(null); } RecipientInfoType type = recipientInfo.Type; switch (type) { case RecipientInfoType.KeyTransport: exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec); break; case RecipientInfoType.KeyAgreement: exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore); break; default: // Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than // returning to the caller. Debug.Fail($"Unexpected RecipientInfoType: {type}"); throw new NotSupportedException(); } if (exception != null) { return(null); } // If we got here, we successfully decrypted. Return the decrypted content. return(_hCryptMsg.GetContentInfo()); } }
public override AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key) { if (key == null) { throw new ArgumentNullException("key"); } RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key); formatter.SetHashAlgorithm("SHA256"); return formatter; }
/// <summary> /// Constructor to obtain API for calling into the Merchant Identifier service /// </summary> /// <param name="consumerKey">Developer Zone consumer key</param> /// <param name="privateKey">PrivateKey</param> /// <param name="environment">Environment.sandbox or Environment.product for sandbox access or production access respectively</param> public MerchantIdentifierService(string consumerKey, AsymmetricAlgorithm privateKey, Environments.Environment environment) : base(consumerKey, privateKey) { this.environment = environment; }
public override void SetKey(AsymmetricAlgorithm key) { ecDsa = EcUtils.ValidateEcDsaKey(key); }
/// <inheritdoc /> public IAsymmetricKeyAlgorithmProvider OpenAlgorithm(AsymmetricAlgorithm algorithm) { return new AsymmetricKeyAlgorithmProvider(algorithm); }
public RewardProgramOfferingsService(Environments.Environment environment, string consumerKey, AsymmetricAlgorithm privateKey) : base(consumerKey, privateKey) { this.environment = environment; }
// Methods public virtual void SetKey(AsymmetricAlgorithm key) { }
private static byte[] CalculateSignerPublicKeyToken(AsymmetricAlgorithm key) { Debug.Assert(key != null, "key != null"); ICspAsymmetricAlgorithm cspAlgorithm = key as ICspAsymmetricAlgorithm; if (cspAlgorithm == null) { return null; } byte[] publicKey = cspAlgorithm.ExportCspBlob(false); SafeAxlBufferHandle tokenBuffer; unsafe { fixed (byte* pPublicKey = publicKey) { // Safe, since we're ensuring the CAPI buffer going in is sized correctly CapiNative.CRYPTOAPI_BLOB keyBlob = new CapiNative.CRYPTOAPI_BLOB(); keyBlob.cbData = publicKey.Length; keyBlob.pbData = new IntPtr(pPublicKey); int hrToken = CapiNative.UnsafeNativeMethods._AxlPublicKeyBlobToPublicKeyToken(ref keyBlob, out tokenBuffer); if (((uint)hrToken & 0x80000000) != 0) { return null; } } } bool acquired = false; RuntimeHelpers.PrepareConstrainedRegions(); try { tokenBuffer.DangerousAddRef(ref acquired); return HexStringToBytes(Marshal.PtrToStringUni(tokenBuffer.DangerousGetHandle())); } finally { if (acquired) { tokenBuffer.DangerousRelease(); } } }
public void Reset () { // note: this call doesn't Reset the X509ChainPolicy if ((status != null) && (status.Length != 0)) status = null; if (elements.Count > 0) elements.Clear (); if (user_root_store != null) { user_root_store.Close (); user_root_store = null; } if (root_store != null) { root_store.Close (); root_store = null; } if (user_ca_store != null) { user_ca_store.Close (); user_ca_store = null; } if (ca_store != null) { ca_store.Close (); ca_store = null; } roots = null; cas = null; collection = null; bce_restriction = null; working_public_key = null; }
/// <summary> /// Returns the string to pass to the platform APIs for a given algorithm. /// </summary> /// <param name="algorithm">The algorithm desired.</param> /// <returns>The platform-specific string to pass to OpenAlgorithm.</returns> private static string GetAlgorithmName(AsymmetricAlgorithm algorithm) { switch (algorithm) { case AsymmetricAlgorithm.DsaSha1: return Platform.AsymmetricAlgorithmNames.DsaSha1; case AsymmetricAlgorithm.DsaSha256: return Platform.AsymmetricAlgorithmNames.DsaSha256; case AsymmetricAlgorithm.EcdsaP256Sha256: return Platform.AsymmetricAlgorithmNames.EcdsaP256Sha256; case AsymmetricAlgorithm.EcdsaP384Sha384: return Platform.AsymmetricAlgorithmNames.EcdsaP384Sha384; case AsymmetricAlgorithm.EcdsaP521Sha512: return Platform.AsymmetricAlgorithmNames.EcdsaP521Sha512; case AsymmetricAlgorithm.RsaOaepSha1: return Platform.AsymmetricAlgorithmNames.RsaOaepSha1; case AsymmetricAlgorithm.RsaOaepSha256: return Platform.AsymmetricAlgorithmNames.RsaOaepSha256; case AsymmetricAlgorithm.RsaOaepSha384: return Platform.AsymmetricAlgorithmNames.RsaOaepSha384; case AsymmetricAlgorithm.RsaOaepSha512: return Platform.AsymmetricAlgorithmNames.RsaOaepSha512; case AsymmetricAlgorithm.RsaPkcs1: return Platform.AsymmetricAlgorithmNames.RsaPkcs1; case AsymmetricAlgorithm.RsaSignPkcs1Sha1: return Platform.AsymmetricAlgorithmNames.RsaSignPkcs1Sha1; case AsymmetricAlgorithm.RsaSignPkcs1Sha256: return Platform.AsymmetricAlgorithmNames.RsaSignPkcs1Sha256; case AsymmetricAlgorithm.RsaSignPkcs1Sha384: return Platform.AsymmetricAlgorithmNames.RsaSignPkcs1Sha384; case AsymmetricAlgorithm.RsaSignPkcs1Sha512: return Platform.AsymmetricAlgorithmNames.RsaSignPkcs1Sha512; case AsymmetricAlgorithm.RsaSignPssSha1: return Platform.AsymmetricAlgorithmNames.RsaSignPssSha1; case AsymmetricAlgorithm.RsaSignPssSha256: return Platform.AsymmetricAlgorithmNames.RsaSignPssSha256; case AsymmetricAlgorithm.RsaSignPssSha384: return Platform.AsymmetricAlgorithmNames.RsaSignPssSha384; case AsymmetricAlgorithm.RsaSignPssSha512: return Platform.AsymmetricAlgorithmNames.RsaSignPssSha512; default: throw new NotSupportedException(); } }
// CTL == Certificate Trust List / NOT SUPPORTED // TODO - check for X509ChainStatusFlags.CtlNotTimeValid // TODO - check for X509ChainStatusFlags.CtlNotSignatureValid // TODO - check for X509ChainStatusFlags.CtlNotValidForUsage private void PrepareForNextCertificate (int n) { X509ChainElement element = elements [n]; X509Certificate2 certificate = element.Certificate; // TODO 6.1.4.a-b // 6.1.4.c working_issuer_name = certificate.SubjectName; // 6.1.4.d-e - our key includes both the public key and it's parameters working_public_key = certificate.PublicKey.Key; // 6.1.4.f // working_public_key_algorithm = certificate.PublicKey.Oid.Value; // TODO 6.1.4.g-j // 6.1.4.k - Verify that the certificate is a CA certificate X509BasicConstraintsExtension bce = (certificate.Extensions["2.5.29.19"] as X509BasicConstraintsExtension); if (bce != null) { if (!bce.CertificateAuthority) { element.StatusFlags |= X509ChainStatusFlags.InvalidBasicConstraints; } } else if (certificate.Version >= 3) { // recent (v3+) CA certificates must include BCE element.StatusFlags |= X509ChainStatusFlags.InvalidBasicConstraints; } // 6.1.4.l - if the certificate isn't self-issued... if (!IsSelfIssued (certificate)) { // ... verify that max_path_length > 0 if (max_path_length > 0) { max_path_length--; } else { // to match MS the reported status must be against the certificate // with the BCE and not where the path is too long. It also means // that this condition has to be reported only once if (bce_restriction != null) { bce_restriction.StatusFlags |= X509ChainStatusFlags.InvalidBasicConstraints; } } } // 6.1.4.m - if pathLengthConstraint is present... if ((bce != null) && (bce.HasPathLengthConstraint)) { // ... and is less that max_path_length, set max_path_length to it's value if (bce.PathLengthConstraint < max_path_length) { max_path_length = bce.PathLengthConstraint; bce_restriction = element; } } // 6.1.4.n - if key usage extension is present... X509KeyUsageExtension kue = (certificate.Extensions["2.5.29.15"] as X509KeyUsageExtension); if (kue != null) { // ... verify keyCertSign is set X509KeyUsageFlags success = X509KeyUsageFlags.KeyCertSign; if ((kue.KeyUsages & success) != success) element.StatusFlags |= X509ChainStatusFlags.NotValidForUsage; } // 6.1.4.o - recognize and process other critical extension present in the certificate ProcessCertificateExtensions (element); }
public DeleteSubscriberIdService(string consumerKey, AsymmetricAlgorithm privateKey, Environments.Environment environment) : base(consumerKey, privateKey) { this.environment = environment; }
public static void NamedAsymmetricAlgorithmCreate_DSA_NotSupported(string identifier) { Assert.Null(AsymmetricAlgorithm.Create(identifier)); }
/// <summary> /// Validate the licence using the specified RSA or DSA public key. /// </summary> /// <returns>The validation status.</returns> /// <param name="publicKey">The public RSA or DSA key used to validate the licence.</param> public ValidationResult Validate(AsymmetricAlgorithm publicKey, bool useNtp = true) { if (publicKey == null) { throw new ArgumentNullException(nameof(publicKey), "Public key cannot be null"); } if (!HasSignature) { return(ValidationResult.NoSignature); } DateTime currentTime = DateTime.UtcNow; try { if (useNtp) { currentTime = NTP.GetNetworkTime(); } } catch { } if (NotAfter != null && currentTime > NotAfter.Value.ToUniversalTime()) { return(ValidationResult.Exipired); } if (NotBefore != null && currentTime < NotBefore.Value.ToUniversalTime()) { return(ValidationResult.NotStarted); } using (SHA512 sha = SHA512.Create()) { byte[] licenceBinary = ToBinary(false); if (publicKey is RSACryptoServiceProvider rsa) { if (rsa.VerifyData(licenceBinary, sha, Signature)) { return(ValidationResult.Valid); } else { return(ValidationResult.InvalidSignature); } } if (publicKey is DSACryptoServiceProvider dsa) { if (dsa.VerifySignature(sha.ComputeHash(licenceBinary), Signature)) { return(ValidationResult.Valid); } else { return(ValidationResult.InvalidSignature); } } throw new NotSupportedException("Only RSA and DSA signatures are supported"); } }
public DSASignatureDeformatter(AsymmetricAlgorithm key) {}
public void TwoCerts_TwoKeys_ManySafeContentsValues(bool invertCertOrder, bool invertKeyOrder) { string pw = nameof(TwoCerts_TwoKeys_ManySafeContentsValues); using (ImportedCollection ic = Cert.Import(TestData.MultiPrivateKeyPfx, null, s_exportableImportFlags)) { X509Certificate2Collection certs = ic.Collection; X509Certificate2 first = certs[0]; X509Certificate2 second = certs[1]; if (invertCertOrder) { X509Certificate2 tmp = first; first = second; second = tmp; } using (AsymmetricAlgorithm firstKey = first.GetRSAPrivateKey()) using (AsymmetricAlgorithm secondKey = second.GetRSAPrivateKey()) { AsymmetricAlgorithm firstAdd = firstKey; AsymmetricAlgorithm secondAdd = secondKey; if (invertKeyOrder != invertCertOrder) { AsymmetricAlgorithm tmp = firstKey; firstAdd = secondAdd; secondAdd = tmp; } Pkcs12Builder builder = new Pkcs12Builder(); Pkcs12SafeContents firstKeyContents = new Pkcs12SafeContents(); Pkcs12SafeContents secondKeyContents = new Pkcs12SafeContents(); Pkcs12SafeContents firstCertContents = new Pkcs12SafeContents(); Pkcs12SafeContents secondCertContents = new Pkcs12SafeContents(); Pkcs12SafeContents irrelevant = new Pkcs12SafeContents(); irrelevant.AddSecret(new Oid("0.0"), new byte[] { 0x05, 0x00 }); Pkcs12SafeBag firstAddedKeyBag = firstKeyContents.AddShroudedKey(firstAdd, pw, s_windowsPbe); Pkcs12SafeBag secondAddedKeyBag = secondKeyContents.AddShroudedKey(secondAdd, pw, s_windowsPbe); Pkcs12SafeBag firstCertBag = firstCertContents.AddCertificate(first); Pkcs12SafeBag secondCertBag = secondCertContents.AddCertificate(second); Pkcs12SafeBag firstKeyBag = firstAddedKeyBag; Pkcs12SafeBag secondKeyBag = secondAddedKeyBag; if (invertKeyOrder != invertCertOrder) { Pkcs12SafeBag tmp = firstKeyBag; firstKeyBag = secondKeyBag; secondKeyBag = tmp; } firstCertBag.Attributes.Add(s_keyIdOne); firstKeyBag.Attributes.Add(s_keyIdOne); Pkcs9LocalKeyId secondKeyId = new Pkcs9LocalKeyId(second.GetCertHash()); secondCertBag.Attributes.Add(secondKeyId); secondKeyBag.Attributes.Add(secondKeyId); // 2C, 1K, 1C, 2K // With some non-participating contents values sprinkled in for good measure. AddContents(irrelevant, builder, pw, encrypt: true); AddContents(secondCertContents, builder, pw, encrypt: true); AddContents(irrelevant, builder, pw, encrypt: false); AddContents(firstKeyContents, builder, pw, encrypt: false); AddContents(firstCertContents, builder, pw, encrypt: true); AddContents(irrelevant, builder, pw, encrypt: false); AddContents(secondKeyContents, builder, pw, encrypt: true); AddContents(irrelevant, builder, pw, encrypt: true); builder.SealWithMac(pw, s_digestAlgorithm, MacCount); byte[] pfxBytes = builder.Encode(); X509Certificate2[] expectedOrder = { first, second }; Action <X509Certificate2> followup = CheckKeyConsistency; // For unknown reasons, CheckKeyConsistency on this test fails // on Windows 7 with an Access Denied in all variations for // Collections, and in invertCertOrder: true for Single. // // Obviously this hit some sort of weird corner case in the Win7 // loader, but it's not important to the test. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !PlatformDetection.IsWindows8xOrLater) { followup = null; } ReadMultiPfx( pfxBytes, pw, first, expectedOrder, followup); } } }
// Methods public abstract virtual void SetKey(AsymmetricAlgorithm key) {}
public KeyDescription(AsymmetricAlgorithm key, string description, int fieldSizeInBits) { Key = key; Description = description; FieldSizeInBits = fieldSizeInBits; }
public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key) { }
/// <summary> /// Initializes a new instance of the <see cref="RsaAsymmetricKeyAlgorithmProvider"/> class. /// </summary> /// <param name="algorithm">The algorithm.</param> public RsaAsymmetricKeyAlgorithmProvider(AsymmetricAlgorithm algorithm) { this.algorithm = algorithm; }
// *** certificate chain/path validation stuff *** // Currently a subset of RFC3280 (hopefully a full implementation someday) private void ValidateChain (X509ChainStatusFlags flag) { // 'n' should be the root certificate... int n = elements.Count - 1; X509Certificate2 certificate = elements [n].Certificate; // ... and, if so, must be treated outside the chain... if (((flag & X509ChainStatusFlags.PartialChain) == 0)) { Process (n); // deal with the case where the chain == the root certificate // (which isn't for RFC3280) part of the chain if (n == 0) { elements [0].UncompressFlags (); return; } // skip the root certificate when processing the chain (in 6.1.3) n--; } // ... unless the chain is a partial one (then we start with that one) // 6.1.1 - Inputs // 6.1.1.a - a prospective certificate path of length n (i.e. elements) // 6.1.1.b - the current date/time (i.e. ChainPolicy.VerificationTime) // 6.1.1.c - user-initial-policy-set (i.e. ChainPolicy.CertificatePolicy) // 6.1.1.d - the trust anchor information (i.e. certificate, unless it's a partial chain) // 6.1.1.e - initial-policy-mapping-inhibit (NOT SUPPORTED BY THE API) // 6.1.1.f - initial-explicit-policy (NOT SUPPORTED BY THE API) // 6.1.1.g - initial-any-policy-inhibit (NOT SUPPORTED BY THE API) // 6.1.2 - Initialization (incomplete) // 6.1.2.a-f - policy stuff, some TODO, some not supported // 6.1.2.g - working public key algorithm // working_public_key_algorithm = certificate.PublicKey.Oid.Value; // 6.1.2.h-i - our key contains both the "working public key" and "working public key parameters" data working_public_key = certificate.PublicKey.Key; // 6.1.2.j - working issuer name working_issuer_name = certificate.IssuerName; // 6.1.2.k - this integer is initialized to n, is decremented for each non-self-issued, certificate and // may be reduced to the value in the path length constraint field max_path_length = n; // 6.1.3 - Basic Certificate Processing // note: loop looks reversed (the list is) but we process this part just like RFC3280 does for (int i = n; i > 0; i--) { Process (i); // 6.1.4 - preparation for certificate i+1 (for not with i+1, or i-1 in our loop) PrepareForNextCertificate (i); } Process (0); // 6.1.3.a.3 - revocation checks CheckRevocationOnChain (flag); // 6.1.5 - Wrap-up procedure WrapUp (); }
public static XmlElement Generate(XmlElement xmlElement, string elementId, AsymmetricAlgorithm signingKey, SignedXml signedXml, string inclusiveNamespacesPrefixList, string digestMethod, string signatureMethod) { return(XmlSignature.Generate(xmlElement, elementId, signingKey, new KeyInfo(), signedXml, inclusiveNamespacesPrefixList, digestMethod, signatureMethod)); }
private bool IsSignedWith (X509Certificate2 signed, AsymmetricAlgorithm pubkey) { if (pubkey == null) return false; // Sadly X509Certificate2 doesn't expose the signature nor the tbs (to be signed) structure MX.X509Certificate mx = signed.MonoCertificate; return (mx.VerifySignature (pubkey)); }