/*public static String GetPublicKey(byte[] data) { OpenCertificate(); X509Certificate2 myCert = new X509Certificate2(data); String publicKey = myCert.GetPublicKeyString(); return publicKey; }*/ public static byte[] GetPublicKey(byte[] data) { OpenCertificate(); X509Certificate2 myCert = new X509Certificate2(data); byte[] publicKey = myCert.GetPublicKey(); return publicKey; }
public static byte[] GetPublicKey(byte[] certDER) { byte[] publickeyDER = null; try { // DERで取得 List <byte> pubkey_pkcs8 = new List <byte>(); { var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certDER); // ここで取れるデータはPKCS#1形式の公開鍵 // 先頭に // 30820122300d06092a864886f70d01010105000382010f00 // を付加するとOpenSSLで取り扱い可能なPKCS#8になる // https://qiita.com/hotpepsi/items/128f3a660cee8b5467c6 byte[] pubkey_pkcs1 = x509.GetPublicKey(); pubkey_pkcs8.AddRange(Common.HexStringToBytes("30820122300d06092a864886f70d01010105000382010f00").ToArray()); pubkey_pkcs8.AddRange(pubkey_pkcs1.ToArray()); } publickeyDER = pubkey_pkcs8.ToArray(); } catch (Exception ex) { logger.Debug(ex); } return(publickeyDER); }
private static HttpStatusCode UploadNewManagementCert(string subscriptionId, X509Certificate2 existingCertificate, string newCertificateCerFilePath) { var statusCode = HttpStatusCode.Unused; var newCertificate = new X509Certificate2(newCertificateCerFilePath); var creds = new CertificateCloudCredentials(subscriptionId, existingCertificate); var client = new ManagementClient(creds); var parm = new ManagementCertificateCreateParameters() { Data = newCertificate.RawData, PublicKey = newCertificate.GetPublicKey(), Thumbprint = newCertificate.Thumbprint }; //Hyak throws an exception for a Created result, which is actually the success code try { var response = client.ManagementCertificates.Create(parm); } catch (CloudException ex) { statusCode = ex.Response.StatusCode; } return statusCode; }
/// <summary> /// 加载密码加密证书 /// </summary> public static RSACryptoServiceProvider initEncryptCert() { X509Certificate2 pc = new X509Certificate2(SDKConfig.EncryptCert); byte[] by=pc.GetPublicKey(); RSACryptoServiceProvider pl = new RSACryptoServiceProvider(); return (RSACryptoServiceProvider)pc.PublicKey.Key; }
static void Main(string[] args) { X509Certificate2 cert = new X509Certificate2(args[0]); SHA256 sha = new SHA256CryptoServiceProvider(); byte[] result = sha.ComputeHash(cert.GetPublicKey()); SoapHexBinary shb = new SoapHexBinary(result); Console.WriteLine(shb.ToString()); }
public MFTestResults CertTest_Test() { bool bRes = true; try { //string filename = "microsoft.cer"; using (Session session = new Session("", MechanismType.RSA_PKCS)) { X509Certificate2 cert = new X509Certificate2(session, Properties.Resources.GetBytes(Properties.Resources.BinaryResources.microsoft)); Log.Comment(cert.Subject); Log.Comment(cert.Issuer); byte[] serialNumber = new byte[cert.GetSerialNumber().Length]; Array.Copy(cert.GetSerialNumber(), 0, serialNumber, 0, cert.GetSerialNumber().Length); PrintByteArray(serialNumber); Log.Comment(cert.GetKeyAlgorithm()); byte[] publicKey = new byte[cert.GetPublicKey().Length]; Array.Copy(cert.GetPublicKey(), 0, publicKey, 0, cert.GetPublicKey().Length); PrintByteArray(publicKey); Log.Comment(cert.GetEffectiveDateString()); Log.Comment(cert.GetExpirationDateString()); } } catch { bRes = false; } return bRes ? MFTestResults.Pass : MFTestResults.Fail; }
public void AnalysePackage(byte[] s_cOneArray) { //取ServerHello中的随机数 Array.ConstrainedCopy(s_cOneArray, 15, scOne.ServerHello.Random_bytes, 0, 28); Array.Copy(scOne.ServerHello.Random_bytes, App.SeverHelloAndClientHelloRandom, 28); Array.Copy(scOne.ServerHello.Random_bytes, 0, App.ClientHelloAndServerHelloRandom, 28, 28); //取ServerHello中的Length Array.ConstrainedCopy(s_cOneArray, 6, scOne.ServerHello.Length, 0, 3); string lengthHEX = JinZhiHelper.DecimalTo2HEX(scOne.ServerHello.Length[0]) + JinZhiHelper.DecimalTo2HEX(scOne.ServerHello.Length[1]) + JinZhiHelper.DecimalTo2HEX(scOne.ServerHello.Length[2]); scOne.ServerHello.LengthValue = Convert.ToInt32(lengthHEX, 16); //取Certificates中的公钥 Array.ConstrainedCopy(s_cOneArray, 5 + 4 + scOne.ServerHello.LengthValue + 15, scOne.Certificate.Certificates, 0, 1376); X509Certificate2 cert = new X509Certificate2(scOne.Certificate.Certificates); scOne.Certificate.SubjectPublicKey = cert.GetPublicKey(); App.PublicKey = cert.PublicKey; }
public static string BuildHashForPublicKey(X509Certificate2 certificate, HashAlgorithm algorithm) { var PUBLIC_KEY_INFO_TYPE = new IntPtr(8); IntPtr publicKeyParametersBuffer = IntPtr.Zero, publicKeyBuffer = IntPtr.Zero, encodingBuffer = IntPtr.Zero; try { var publicKey = certificate.GetPublicKey(); publicKeyParametersBuffer = Marshal.AllocCoTaskMem(certificate.PublicKey.EncodedParameters.RawData.Length); publicKeyBuffer = Marshal.AllocCoTaskMem(publicKey.Length); Marshal.Copy(certificate.PublicKey.EncodedParameters.RawData, 0, publicKeyParametersBuffer, certificate.PublicKey.EncodedParameters.RawData.Length); Marshal.Copy(publicKey, 0, publicKeyBuffer, publicKey.Length); var publicKeyInfo = new CERT_PUBLIC_KEY_INFO(); publicKeyInfo.Algorithm = new CRYPT_ALGORITHM_IDENTIFIER(); publicKeyInfo.PublicKey = new CRYPT_BIT_BLOB(); publicKeyInfo.Algorithm.pszObjId = certificate.PublicKey.EncodedKeyValue.Oid.Value; publicKeyInfo.Algorithm.Parameters = new CRYPT_OBJID_BLOB(); publicKeyInfo.PublicKey.cbData = (uint)publicKey.Length; publicKeyInfo.PublicKey.cUnusedBits = 0; publicKeyInfo.PublicKey.pbData = publicKeyBuffer; publicKeyInfo.Algorithm.Parameters.cbData = (uint)certificate.PublicKey.EncodedParameters.RawData.Length; publicKeyInfo.Algorithm.Parameters.pbData = publicKeyParametersBuffer; uint size = 0; if (Crypto32.CryptEncodeObject(1, PUBLIC_KEY_INFO_TYPE, publicKeyInfo, IntPtr.Zero, ref size)) { encodingBuffer = Marshal.AllocCoTaskMem((int)size); if (Crypto32.CryptEncodeObject(1, PUBLIC_KEY_INFO_TYPE, publicKeyInfo, encodingBuffer, ref size)) { var encoded = new byte[size]; Marshal.Copy(encodingBuffer, encoded, 0, encoded.Length); return Convert.ToBase64String(algorithm.ComputeHash(encoded)); } } } finally { Marshal.FreeCoTaskMem(publicKeyParametersBuffer); Marshal.FreeCoTaskMem(encodingBuffer); Marshal.FreeCoTaskMem(publicKeyBuffer); } return null; }
/// <summary> /// Gets the <see cref="DSA" /> public key from the certificate or null if the certificate does not have a DSA public key. /// </summary> public static DSA GetDSAPublicKey(this X509Certificate2 certificate) { return(certificate.GetPublicKey <DSA>()); }
/// <summary> /// Checks that two certificate are equal. Verifies that the public keys and expiration dates for /// <paramref /// name="first" /> /// and /// <paramref /// name="second" /> /// are the same. /// </summary> /// <param name="first"> The first certificate to compare </param> /// <param name="second"> The second certificate to compare </param> /// <returns> True if the certificates are equal, otherwise false </returns> public static bool IsEqualTo(this X509Certificate2 first, X509Certificate2 second) { return first.GetPublicKey() == second.GetPublicKey() && first.NotAfter == second.NotAfter; }
public static void SignXml(ref XmlDocument document, X509Certificate2 certificate, RequestType requestType) { document.PreserveWhitespace = true; if (requestType == RequestType.Invoice || requestType == RequestType.Buisness_premise) { XmlNode nodeTaxNumber = document.GetElementsByTagName("fu:TaxNumber")[0]; nodeTaxNumber.InnerText = AppLink.VATNumber; string taxNumber = nodeTaxNumber.InnerText; if (requestType == RequestType.Invoice) { string issueDate = DateTime.Now.ToUniversalTime().ToString("s"); XmlNode nodeIssueDate = document.GetElementsByTagName("fu:IssueDateTime")[0]; nodeIssueDate.InnerText = issueDate; XmlNode nodeInvoiceNumber = document.GetElementsByTagName("fu:InvoiceNumber")[0]; string invoiceNumber = nodeInvoiceNumber.InnerText; XmlNode nodeBusinessPremiseID = document.GetElementsByTagName("fu:BusinessPremiseID")[0]; string businessPremiseID = nodeBusinessPremiseID.InnerText; XmlNode nodeElectronicDeviceID = document.GetElementsByTagName("fu:ElectronicDeviceID")[0]; string electronicDeviceID = nodeElectronicDeviceID.InnerText; XmlNode nodeInvoiceAmount = document.GetElementsByTagName("fu:InvoiceAmount")[0]; string invoiceAmount = nodeInvoiceAmount.InnerText; string zoi = CalculateZOI(taxNumber, issueDate, invoiceNumber, businessPremiseID, electronicDeviceID, invoiceAmount, certificate); XmlNode nodeZoi = document.GetElementsByTagName("fu:ProtectedID")[0]; nodeZoi.InnerText = zoi; } } CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); if (document == null) throw new ArgumentException("xmlDoc"); // Create a SignedXml object. SignedXml signedXml = new SignedXml(document); byte[] data = certificate.GetPublicKey(); string base64 = Convert.ToBase64String(data); RSACryptoServiceProvider rsaCSP = (RSACryptoServiceProvider)certificate.PrivateKey; CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = rsaCSP.CspKeyContainerInfo.KeyContainerName; cspParameters.KeyNumber = rsaCSP.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2; RSACryptoServiceProvider rsaAesCSP = new RSACryptoServiceProvider(cspParameters); signedXml.SigningKey = rsaAesCSP; //newKey; KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(); keyInfoData.AddIssuerSerial(certificate.Issuer, certificate.SerialNumber); X509Extension extension = certificate.Extensions[1]; AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData); keyInfoData.AddSubjectName(certificate.SubjectName.Name); // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = "#test"; reference.DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256"; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); XmlNode element; if (requestType == RequestType.Invoice) { element = document.GetElementsByTagName("fu:InvoiceRequest")[0]; } else { element = document.GetElementsByTagName("fu:BusinessPremiseRequest")[0]; } element.AppendChild(xmlDigitalSignature); }
// Filters the given list of certificates down to only the certificates that match the given certificate. private void FindMatchingCertificates(List<X509Certificate2> certificates, X509Certificate2 certificate) { byte[] hash = certificate.GetCertHash(); byte[] key = certificate.GetPublicKey(); for (int i = certificates.Count - 1; i >= 0; i--) { if (!hash.SequenceEqual(certificates[i].GetCertHash()) || !key.SequenceEqual(certificates[i].GetPublicKey())) certificates.RemoveAt(i); } }
/// <summary> /// Verifies the PK fingerprint. /// </summary> /// <returns><c>true</c>, if PK fingerprint was verifyed, <c>false</c> otherwise.</returns> /// <param name="endCert">End cert.</param> /// <param name="requestUri">Request URI.</param> private static bool VerifyPublicKey(System.Security.Cryptography.X509Certificates.X509Certificate endCert, String requestUri) { SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation VerifyPublicKey "+ requestUri); string[] publickey = null; foreach(KeyValuePair<string, string[]> entry in IPhoneIO.PublicKey) { if(requestUri.StartsWith(entry.Key)) { SystemLogger.Log (SystemLogger.Module.PLATFORM, "*** found fingerprint to check for requestUri: ["+requestUri+"]"); publickey = new string[entry.Value.Length]; int i = 0; foreach (string fprint in entry.Value) { publickey[i] = ToThumbprint (fprint); } } } if (publickey != null) { W.X509Certificate2 certificateThumb = new W.X509Certificate2 (endCert); var PublicThumb = BitConverter.ToString (certificateThumb.GetPublicKey ()).Replace ("-", ""); //SystemLogger.Log (SystemLogger.Module.PLATFORM, "**************** Certificate PublicThumb: [" + PublicThumb + "]"); //SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation io-services-config publickey: [" + string.Join(",", publickey) + "]"); if (!publickey.Contains (PublicThumb)) { SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation Public Key ERROR!!!"); return false; } } else { SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** WARNING!! Certificate Validation Public Key NOT FOUND!!! (you should provide a valid fingerprint in your io-sevices-config.xml file in order to validate HTTPS web certificates)"); return false; } return true; }
/// <summary> /// Gets the <see cref="ECDsa" /> public key from the certificate or null if the certificate does not have an ECDsa public key. /// </summary> public static ECDsa?GetECDsaPublicKey(this X509Certificate2 certificate) { return(certificate.GetPublicKey <ECDsa>(cert => HasECDsaKeyUsage(cert))); }
/// <summary> /// Gets the <see cref="Gost3410" /> public key from the certificate or null if the certificate does not have an Gost3410 public key. /// </summary> public static Gost3410 GetGost3410PublicKey(this X509Certificate2 certificate) { return(certificate.GetPublicKey <Gost3410>()); }
/// <summary> /// Gets the <see cref="Gost3410_2012_512" /> public key from the certificate or null if the certificate does not have an Gost3410 public key. /// </summary> public static Gost3410_2012_512 GetGost3410_2012_512PublicKey(this X509Certificate2 certificate) { return(certificate.GetPublicKey <Gost3410_2012_512>()); }
public static ECDsa GetECDsaPublicKey(this X509Certificate2 certificate) { return(certificate.GetPublicKey <ECDsa>()); }
/// <summary> /// Encrypts a value using the requested certificate. /// The certificate must have a valid RSA public key. /// </summary> /// <param name="value">The value to be encrypted.</param> /// <param name="certificate">The certificate used to encrypt the value.</param> /// <remarks> /// First a cryptographically random AES key is generated. /// The value is encrypted using that AES key. /// The AES key is then encrypted using the RSA key from the certificate. /// Then the encrypted value is joined with the encrypted AES key. /// That result is base 64 encoded and returned. /// /// The format of the result in binary (before base 64 encoding) is the following: /// [AES key length in bytes] - Length: 4 bytes /// [AES block size in bytes] - Length: 4 bytes /// [AES key encrypted length in bytes] - Length: 4 bytes /// [AES initialization vector encrypted length in bytes] - Length: 4 bytes /// [Certificate public key length in bytes] - Length: 4 bytes /// [Certificate public key] - Length: Public key length /// [Encrypted AES key] - Length: AES key encrypted length bytes /// [Encrypted AES initialization vector] - Length: AES Block size bytes /// [Encrypted value] - Length: remaining data length /// </remarks> /// <returns>The encrypted, base64-encoded value.</returns> public static string Encrypt(string value, X509Certificate2 certificate) { const int keySizeBits = 256; const int keySizeBytes = keySizeBits / 8; const int blockSizeBits = 128; const int blockSizeBytes = blockSizeBits / 8; // Get the RSA key from the certificate var rsa = certificate.PublicKey.Key as RSACryptoServiceProvider; if (rsa == null) { throw new InvalidOperationException("Certificate does not contain an RSA public key."); } // Get the public key as a byte array var publicKey = certificate.GetPublicKey(); using (var aes = new AesManaged { KeySize = keySizeBits, BlockSize = blockSizeBits, Mode = CipherMode.CBC }) { // Generate a cryptographically random initialization vector and key aes.GenerateIV(); aes.GenerateKey(); if (aes.IV.Length != blockSizeBytes) { throw new InvalidOperationException("AES IV size is not equal to the block size."); } // Encrypt the AES key and initialization vector var keyBytes = rsa.Encrypt(aes.Key, false); var ivBytes = rsa.Encrypt(aes.IV, false); using (var memory = new MemoryStream()) { // Write the AES key length and block size memory.WriteInt(keySizeBytes); memory.WriteInt(blockSizeBytes); // Write the sizes of the encrypted AES key and initialization vector memory.WriteInt(keyBytes.Length); memory.WriteInt(ivBytes.Length); // Write the size of the certificate public key memory.WriteInt(publicKey.Length); // Write the public key memory.Write(publicKey, 0, publicKey.Length); // Write the encrypted AES key and initialization vector memory.Write(keyBytes, 0, keyBytes.Length); memory.Write(ivBytes, 0, ivBytes.Length); // Encrypt and write the actual value using the aes encryption using (var transform = aes.CreateEncryptor()) using (var crypto = new CryptoStream(memory, transform, CryptoStreamMode.Write)) { var bytes = Encoding.UTF8.GetBytes(value); crypto.Write(bytes, 0, bytes.Length); crypto.FlushFinalBlock(); } // Return the base 64 encoded result return Convert.ToBase64String(memory.ToArray(), Base64FormattingOptions.InsertLineBreaks); } } }
/// <summary> /// Gets the <see cref="RSA" /> public key from the certificate or null if the certificate does not have an RSA public key. /// </summary> public static RSA?GetRSAPublicKey(this X509Certificate2 certificate) { return(certificate.GetPublicKey <RSA>()); }
private static string Rfc4050XmlMaker(string algo, DerObjectIdentifier keyAlgoOid, X509Certificate2 cert) { if (!algo.Equals("ECDH", StringComparison.InvariantCultureIgnoreCase) && !algo.Equals("ECDSA", StringComparison.InvariantCultureIgnoreCase)) throw new Exception("Cannot generate rfc4050 keys for unknown EC algorithm"); algo = algo.ToUpper(); var namedCurve = SecNamedCurves.GetByOid(keyAlgoOid); var publickey = new ECPublicKeyParameters(algo, namedCurve.Curve.DecodePoint(cert.GetPublicKey()), // Q keyAlgoOid); //now we have the public key in bouncy castle //we can create the xml to import to CngKey string xml = "<" + algo + @"KeyValue xmlns='http://www.w3.org/2001/04/xmldsig-more#'> <DomainParameters> <NamedCurve URN='urn:oid:" + keyAlgoOid.Id + @"' /> </DomainParameters> <PublicKey> <X Value='" + publickey.Q.X.ToBigInteger() + @"' xsi:type='PrimeFieldElemType' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' /> <Y Value='" + publickey.Q.Y.ToBigInteger() + @"' xsi:type='PrimeFieldElemType' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' /> </PublicKey> </" + algo + "KeyValue>"; return xml; }