/// <summary> /// 初始化加密证书 /// </summary> private static void InitEncryptCert() { if (SdkConfig.EncryptCert == null) { Log.Info("未配置加密证书路径,不做初始化。"); return; } Log.Info("读取加密证书……"); FileStream fileStream = null; try { fileStream = new FileStream(SdkConfig.EncryptCert, FileMode.Open); X509Certificate cert = new X509CertificateParser().ReadCertificate(fileStream); _encryptCert = new Cert(); _encryptCert.X509Certificate = cert; _encryptCert.CertId = cert.SerialNumber.ToString(); _encryptCert.AsymmetricKey = cert.GetPublicKey(); Log.Info("加密证书读取成功,序列号:" + _encryptCert.CertId); } finally { if (fileStream != null) { fileStream.Close(); } } }
private static void initCerCerts() { log.Info("读取验签证书文件夹下所有cer文件……"); DirectoryInfo directory = new DirectoryInfo(SDKConfig.ValidateCertDir); FileInfo[] files = directory.GetFiles("*.cer"); if (null == files || 0 == files.Length) { log.Info("请确定[" + SDKConfig.ValidateCertDir + "]路径下是否存在cer文件"); return; } foreach (FileInfo file in files) { FileStream fileStream = null; try { fileStream = new FileStream(file.DirectoryName + "\\" + file.Name, FileMode.Open); X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream); Cert cert = new Cert(); cert.cert = certificate; cert.certId = certificate.SerialNumber.ToString(); cert.key = certificate.GetPublicKey(); cerCerts[cert.certId] = cert; log.Info(file.Name + "读取成功,序列号:" + cert.certId); } finally { if (fileStream != null) { fileStream.Close(); } } } }
private bool ValidateAppResponse(string jsonData, Encoding encoding) { //获取签名 Dictionary <string, object> data = SDKUtil.JsonToDictionary(jsonData); string dataString = (string)data["data"]; string signString = (string)data["sign"]; byte[] signByte = Convert.FromBase64String(signString); byte[] dataByte = encoding.GetBytes(dataString); IDigest digest = DigestUtilities.GetDigest("SHA1"); digest.BlockUpdate(dataByte, 0, dataByte.Length); byte[] dataDigest = DigestUtilities.DoFinal(digest); string digestString = BitConverter.ToString(dataDigest).Replace("-", "").ToLower(); if (appVerifyPubKey == null) { using (FileStream fileStream = new FileStream("d:/certs/acp_test_app_verify_sign.cer", FileMode.Open))//TODO: 这个是测试环境的证书,切换生产需要改生产证书。 { X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream); this.appVerifyPubKey = certificate.GetPublicKey(); } } byte[] digestByte = encoding.GetBytes(digestString); ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA"); verifier.Init(false, this.appVerifyPubKey); verifier.BlockUpdate(digestByte, 0, digestByte.Length); return(verifier.VerifySignature(signByte)); }
public static bool ValidateCertificates(X509Certificate2 cert) { var pathCA = Directory.GetCurrentDirectory() + "/../../CryptoFiles/rootca.pem"; var caCertificate = new X509CertificateParser().ReadCertificate(File.ReadAllBytes(pathCA)); var pathCRL = Directory.GetCurrentDirectory() + "/../../CryptoFiles/crl/list.pem"; var crl = new X509CrlParser().ReadCrl(File.ReadAllBytes(pathCRL)); var receiverCert = new X509CertificateParser().ReadCertificate(cert.GetRawCertData()); try { receiverCert.Verify(caCertificate.GetPublicKey()); } catch { MessageBox.Show("Receiver's certificate is not signed by CA!"); return(false); } if (crl.IsRevoked(receiverCert)) { MessageBox.Show("Receiver's certificate is revoked!"); return(false); } return(true); }
public static X509Certificate2 CreateSelfSignedClientCertificate(string commonNameValue, RavenServer.CertificateHolder certificateHolder, out byte[] certBytes) { var serverCertBytes = certificateHolder.Certificate.Export(X509ContentType.Cert); var readCertificate = new X509CertificateParser().ReadCertificate(serverCertBytes); CreateSelfSignedCertificateBasedOnPrivateKey( commonNameValue, readCertificate.SubjectDN, (certificateHolder.PrivateKey.Key, readCertificate.GetPublicKey()), true, false, 5, out certBytes); ValidateNoPrivateKeyInServerCert(serverCertBytes); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); var serverCert = DotNetUtilities.FromX509Certificate(certificateHolder.Certificate); store.Load(new MemoryStream(certBytes), Array.Empty <char>()); store.SetCertificateEntry(serverCert.SubjectDN.ToString(), new X509CertificateEntry(serverCert)); var memoryStream = new MemoryStream(); store.Save(memoryStream, Array.Empty <char>(), GetSeededSecureRandom()); certBytes = memoryStream.ToArray(); var cert = new X509Certificate2(certBytes, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); return(cert); }
static void CheckValidityOfResponse(CertID id, BasicOcspResp responseObject, Ca ca) { var inputStream = new MemoryStream(responseObject.GetEncoded()); var asn1Sequence = (Asn1Sequence) new Asn1InputStream(inputStream).ReadObject(); var response = BasicOcspResponse.GetInstance(asn1Sequence); var ocspChain = CreateOcspCertificateChain(ca); if (ocspChain.Length == 0) { throw new OcspException("OCSP certificate chain is invalid"); } var ocesOcspCertificate = OcesCertificateFactory.Instance.Generate(CompleteOcspChain(response, ocspChain)); CheckBasicOcspResp(id, responseObject, ocesOcspCertificate, ca); var signingCertificate = new X509CertificateParser().ReadCertificate(response.Certs[0].GetEncoded()); var issuingCertificate = new X509CertificateParser().ReadCertificate(ocspChain[0].GetRawCertData()); signingCertificate.Verify(issuingCertificate.GetPublicKey()); if (!responseObject.Verify(signingCertificate.GetPublicKey())) { throw new OcspException("Signature is invalid"); } }
private static void initEncryptCert() { log.Info("读取加密证书……"); FileStream fileStream = null; try { fileStream = new FileStream(SDKConfig.EncryptCert, FileMode.Open); X509Certificate cert = new X509CertificateParser().ReadCertificate(fileStream); encryptCert = new Cert(); encryptCert.cert = cert; encryptCert.certId = cert.SerialNumber.ToString(); encryptCert.key = cert.GetPublicKey(); log.Info("加密证书读取成功,序列号:" + encryptCert.certId); } finally { if (fileStream != null) { fileStream.Close(); } } }
private DsaPublicKeyParameters GetInheritedKey(DsaPublicKeyParameters dsaPubKey) { X509Certificate cert = new X509CertificateParser().ReadCertificate( GetRfc4134Data("CarlDSSSelf.cer")); DsaParameters dsaParams = ((DsaPublicKeyParameters)cert.GetPublicKey()).Parameters; return(new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams)); }
private (AsymmetricCipherKeyPair keyPair, X509Name subject) GetSigningKeyPair(X509Certificate2 signingCert) { X509Certificate publicPartCertificate = new X509CertificateParser().ReadCertificate(signingCert.RawData); AsymmetricKeyParameter privateKey = ExtractPrivateKey(signingCert, publicPartCertificate); var keyPair = new AsymmetricCipherKeyPair(publicPartCertificate.GetPublicKey(), privateKey); return(keyPair, publicPartCertificate.SubjectDN); }
public static UnionPayCertificate GetCertificate(string certificate) { var stream = File.Exists(certificate) ? File.OpenRead(certificate) : (Stream) new MemoryStream(Convert.FromBase64String(certificate)); var cert = new X509CertificateParser().ReadCertificate(stream); return(new UnionPayCertificate { key = cert.GetPublicKey(), cert = cert, certId = cert.SerialNumber.ToString() }); }
public static UnionPayCertificate GetCertificate(string certificate) { var stream = new MemoryStream(Convert.FromBase64String(certificate)); var x509certificate = new X509CertificateParser().ReadCertificate(stream); return(new UnionPayCertificate { key = x509certificate.GetPublicKey(), cert = x509certificate, certId = x509certificate.SerialNumber.ToString() }); }
public static X509Certificate2 CreateSelfSignedExpiredClientCertificate(string commonNameValue, RavenServer.CertificateHolder certificateHolder) { var readCertificate = new X509CertificateParser().ReadCertificate(certificateHolder.Certificate.Export(X509ContentType.Cert)); return(CreateSelfSignedCertificateBasedOnPrivateKey( commonNameValue, readCertificate.SubjectDN, (certificateHolder.PrivateKey.Key, readCertificate.GetPublicKey()), true, false, -1, out _)); }
private bool VerificaEmisorCertificado(byte[] certificado, byte[] certificadoAC) { Org.BouncyCastle.X509.X509Certificate cer1 = new X509CertificateParser().ReadCertificate(certificado); Org.BouncyCastle.X509.X509Certificate cer2 = new X509CertificateParser().ReadCertificate(certificadoAC); try { cer1.Verify(cer2.GetPublicKey()); return(true); } catch (Exception ee) { //Logger.Error(ee); return(false); } }
private void VerifyCrl(X509Certificate2 certificate) { var bcIssuingCaCert = new X509CertificateParser().ReadCertificate(certificate.RawData); try { _crl.Verify(bcIssuingCaCert.GetPublicKey()); } catch (SignatureException e) { throw new InvalidSignatureException("CRL Issued by" + _crl.IssuerDN + " does not have valid signature by certificate's issuer certificate " + certificate.IssuerName, e); } }
public static X509Certificate2 CreateSelfSignedExpiredClientCertificate(string commonNameValue, RavenServer.CertificateHolder certificateHolder) { var readCertificate = new X509CertificateParser().ReadCertificate(certificateHolder.Certificate.Export(X509ContentType.Cert)); CreateSelfSignedCertificateBasedOnPrivateKey( commonNameValue, readCertificate.SubjectDN, (certificateHolder.PrivateKey.Key, readCertificate.GetPublicKey()), true, false, -1, out var certBytes); return(new X509Certificate2(certBytes, (string)null, X509KeyStorageFlags.MachineKeySet)); }
public static bool VerifySignature(byte[] certificate, byte[] signature, byte[] data) { var cert = new X509CertificateParser().ReadCertificate(certificate); // https://stackoverflow.com/questions/12263641/digital-signature-verification-using-bouncycastle-ecdsa-with-sha-256-c-sharp // https://stackoverflow.com/a/29574548/141927 ECPublicKeyParameters ecPublic = (ECPublicKeyParameters)cert.GetPublicKey(); ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA"); signer.Init(false, ecPublic); signer.BlockUpdate(data, 0, data.Length); return(signer.VerifySignature(derEncodeSignature(signature))); }
public override VerifyResult Validate(SigType type, byte[] tbsContent, byte[] signedValue) { if (type == SigType.Sign) { throw new ArgumentOutOfRangeException(nameof(type), "签名类型(type)必须是 Seal,不支持电子印章验证"); } // 计算原文摘要 GeneralDigest md = new SM3Digest(); md.BlockUpdate(tbsContent, 0, tbsContent.Length); byte[] expect = new byte[32]; md.DoFinal(expect, 0); SesSignature sesSignature = SesSignature.GetInstance(signedValue); TbsSign toSign = sesSignature.ToSign; byte[] expectDataHash = toSign.DataHash.GetOctets(); // 比较原文摘要 if (!Arrays.AreEqual(expect, expectDataHash)) { return(VerifyResult.SignedTampered); } // 预期的电子签章数据,签章值 byte[] expSigVal = sesSignature.Signature.GetOctets(); ISigner sg = SignerUtilities.GetSigner(toSign.SignatureAlgorithm); byte[] certDer = toSign.Cert.GetOctets(); // 构造证书对象 X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(certDer); AsymmetricKeyParameter p = x509Certificate.GetPublicKey(); sg.Init(false, p); byte[] input = toSign.GetDerEncoded(); sg.BlockUpdate(input, 0, input.Length); if (!sg.VerifySignature(expSigVal)) { return(VerifyResult.SignedTampered); } return(VerifyResult.Success); }
private static void InitCerCerts() { if (SdkConfig.ValidateCertDir == null) { Log.Info("未配置验签证书路径,不做初始化。"); return; } Log.Info("读取验签证书文件夹下所有cer文件……"); DirectoryInfo directory = new DirectoryInfo(SdkConfig.ValidateCertDir); FileInfo[] files = directory.GetFiles("*.cer"); if (0 == files.Length) { Log.Info("请确定[" + SdkConfig.ValidateCertDir + "]路径下是否存在cer文件"); return; } foreach (FileInfo file in files) { FileStream fileStream = null; try { using (fileStream = new FileStream(file.DirectoryName + "\\" + file.Name, FileMode.Open)) { X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream); Cert cert = new Cert { X509Certificate = certificate, CertId = certificate.SerialNumber.ToString(), AsymmetricKey = certificate.GetPublicKey() }; CerCerts[cert.CertId] = cert; Log.Info(file.Name + "读取成功,序列号:" + cert.CertId); } } finally { if (fileStream != null) { fileStream.Close(); } } } }
/// <summary> /// Verifies the signature on the CRL. /// </summary> public bool VerifySignature(X509Certificate2 issuer, bool throwOnError) { m_issuer = issuer; try { Org.BouncyCastle.X509.X509Certificate bccert = new X509CertificateParser().ReadCertificate(issuer.RawData); m_crl.Verify(bccert.GetPublicKey()); } catch (Exception) { if (throwOnError) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Could not verify signature on CRL."); } return(false); } return(true); }
public static List <IObjectAttribute> GetTestUserRsaPubKeyAttributes(ISession session, string label, string labelSuffix) { X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(Encoding.ASCII.GetBytes(TestUserRsaCert)); var rsaPubKeyParams = x509Certificate.GetPublicKey() as RsaKeyParameters; return(new List <IObjectAttribute>() { session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PUBLIC_KEY), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_PRIVATE, false), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_MODIFIABLE, true), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, label + labelSuffix), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_ID, Encoding.ASCII.GetBytes(label)), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_KEY_TYPE, CKK.CKK_RSA), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_MODULUS, rsaPubKeyParams.Modulus.ToByteArrayUnsigned()), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_PUBLIC_EXPONENT, rsaPubKeyParams.Exponent.ToByteArrayUnsigned()) }); }
public static List <IObjectAttribute> GetTestUserEcdsaPubKeyAttributes(ISession session, string label, string labelSuffix) { X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(Encoding.ASCII.GetBytes(TestUserEcdsaCert)); var ecdsaPubKeyParams = x509Certificate.GetPublicKey() as ECPublicKeyParameters; return(new List <IObjectAttribute>() { session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PUBLIC_KEY), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_PRIVATE, false), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_MODIFIABLE, true), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, label + labelSuffix), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_ID, Encoding.ASCII.GetBytes(label)), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_KEY_TYPE, CKK.CKK_EC), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_EC_PARAMS, ecdsaPubKeyParams.PublicKeyParamSet.GetDerEncoded()), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_EC_POINT, new X9ECPoint(ecdsaPubKeyParams.Q).GetDerEncoded()) }); }
static bool IsSelfSigned(X509Certificate2 certificate) { try { var bcCertificate = new X509CertificateParser().ReadCertificate(certificate.RawData); bcCertificate.Verify(bcCertificate.GetPublicKey()); return(true); } catch (InvalidKeyException) { } catch (CertificateException) { } catch (SignatureException) { } return(false); }
protected void btnRead_Click(object sender, EventArgs e) { log.Info("读取验签证书文件夹" + (Server.MapPath("~/") + "Cert/") + "下所有cer文件……"); DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/") + "Cert/"); FileInfo[] files = directory.GetFiles("*.cer"); if (null == files || 0 == files.Length) { log.Info("请确定[" + (Server.MapPath("~/") + "Cert/") + "]路径下是否存在cer文件"); return; } foreach (FileInfo file in files) { FileStream fileStream = null; try { string FilePath = file.DirectoryName + "\\" + file.Name; log.Info("找到验签证书文件" + file.DirectoryName + "\\" + file.Name); fileStream = new FileStream(FilePath, FileMode.Open); log.Info("验签证书文件fileStream"); X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream); log.Info("验签证书文件X509Certificate读取完成"); Cert cert = new Cert(); cert.cert = certificate; cert.certId = certificate.SerialNumber.ToString(); log.Info("验签证书文件X509Certificate>>>cert.certId=" + certificate.SerialNumber.ToString()); cert.key = certificate.GetPublicKey(); log.Info("验签证书文件X509Certificate>>>cert.Key读取完成"); cerCerts[cert.certId] = cert; log.Info(file.Name + "读取成功,序列号:" + cert.certId); } finally { if (fileStream != null) { fileStream.Close(); } } } }
private static void initEncryptCert() { string certPath = SDKConfig.EncryptCert; if (certPath == null) { log.Info("未配置加密证书路径,不做初始化。"); return; } log.Info("读取加密证书:" + certPath); FileStream fileStream = null; try { fileStream = new FileStream(certPath, FileMode.Open, FileAccess.Read); X509Certificate cert = new X509CertificateParser().ReadCertificate(fileStream); encryptCert = new Cert(); encryptCert.cert = cert; encryptCert.certId = cert.SerialNumber.ToString(); encryptCert.key = cert.GetPublicKey(); log.Info("加密证书读取成功,序列号:" + encryptCert.certId); } catch (Exception e) { log.Error("加密证书读取失败,异常:" + e); } finally { if (fileStream != null) { fileStream.Close(); } } }
public override async Task PairAsync(string ipAddress, TextBox outputTextBox) { // Create SHA256 hash digest. This is not supported by server version < 7 // (need to use SHA1 for those cases) but that doesn't really matter right now. IDigest hashAlgorithm = new Sha256Digest(); int hashDigestSize = hashAlgorithm.GetDigestSize(); // Create and salt pin byte[] salt = this.GenerateRandomBytes(16); string pin = GenerateRandomPin(); byte[] saltAndPin = SaltPin(salt, pin); // Asymmetric key pair RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(new KeyGenerationParameters(this.SecureRandom, 2048)); AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair(); // Certificate issuer and name X509Name name = new X509Name("CN=NVIDIA GameStream Client"); // Certificate serial number byte[] serialBytes = this.GenerateRandomBytes(8); BigInteger serial = new BigInteger(serialBytes).Abs(); // Expires in 20 years DateTime now = DateTime.UtcNow; DateTime expiration = now.AddYears(20); X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); generator.SetSubjectDN(name); generator.SetIssuerDN(name); generator.SetSerialNumber(serial); generator.SetNotBefore(now); generator.SetNotAfter(expiration); generator.SetPublicKey(keyPair.Public); BouncyCastleX509Certificate certificate = generator.Generate( new Asn1SignatureFactory("SHA1WithRSA", keyPair.Private)); // Create PKCS12 certificate bytes. Pkcs12Store store = new Pkcs12Store(); X509CertificateEntry certificateEntry = new X509CertificateEntry(certificate); string friendlyName = "Moonlight Xbox"; string password = "******"; store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry( friendlyName, new AsymmetricKeyEntry(keyPair.Private), new X509CertificateEntry[] { certificateEntry }); string pfxData; using (MemoryStream memoryStream = new MemoryStream(512)) { store.Save(memoryStream, password.ToCharArray(), this.SecureRandom); pfxData = CryptographicBuffer.EncodeToBase64String(memoryStream.ToArray().AsBuffer()); } await CertificateEnrollmentManager.ImportPfxDataAsync( pfxData, password, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.DeleteExpired, friendlyName); // Read the UWP cert from the cert store Certificate uwpCertificate = (await CertificateStores.FindAllAsync( new CertificateQuery { FriendlyName = friendlyName }))[0]; string keyString; using (StringWriter keyWriter = new StringWriter()) { PemWriter pemWriter = new PemWriter(keyWriter); pemWriter.WriteObject(keyPair); keyString = keyWriter.ToString(); // Line endings must be UNIX style for GFE to accept the certificate. keyString = keyString.Replace(Environment.NewLine, "\n"); } string certString; using (StringWriter certWriter = new StringWriter()) { PemWriter pemWriter = new PemWriter(certWriter); pemWriter.WriteObject(certificate); certString = certWriter.ToString(); // Line endings must be UNIX style for GFE to accept the certificate. certString = certString.Replace(Environment.NewLine, "\n"); } byte[] pemCertBytes = Encoding.UTF8.GetBytes(certString); byte[] uniqueId = GenerateRandomBytes(8); // Create the HTTP client. HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); filter.ClientCertificate = uwpCertificate; HttpClient httpClient = new HttpClient(filter); // Unpair before doing anything else in this test app. string uriString = string.Format( "http://{0}:47989/unpair?uniqueid={1}&uuid={2}", ipAddress, BytesToHex(uniqueId), Guid.NewGuid().ToString("N")); using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString))) { using (HttpResponseMessage response = await httpClient.SendRequestAsync(request)) { outputTextBox.Text = $"Unpair status code: {response.StatusCode}\n"; string responseContent = await response.Content.ReadAsStringAsync(); outputTextBox.Text += responseContent + "\n"; } } await Task.Delay(2000); outputTextBox.Text = $"Enter pin: {pin}"; // Get server certificate. // TODO: Call should have no timeout because it requires the user to enter a pin. PairResponse pairResponse = null; uriString = string.Format( "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&phrase=getservercert&salt={3}&clientcert={4}", ipAddress, BytesToHex(uniqueId), Guid.NewGuid().ToString("N"), BytesToHex(salt), BytesToHex(pemCertBytes)); using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString))) { using (HttpResponseMessage response = await httpClient.SendRequestAsync(request)) { outputTextBox.Text = $"Get server cert status code: {response.StatusCode}\n"; string responseContent = await response.Content.ReadAsStringAsync(); outputTextBox.Text += responseContent + "\n"; using (StringReader reader = new StringReader(responseContent)) { XmlSerializer serializer = new XmlSerializer(typeof(PairResponse)); pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse; } } } if (pairResponse == null || pairResponse.Paired != 1) { outputTextBox.Text += "Pairing failed.\n"; return; } if (string.IsNullOrEmpty(pairResponse.PlainCert)) { outputTextBox.Text += "Pairing already in progress.\n"; return; } // Parse server certificate byte[] serverCertBytes = HexToBytes(pairResponse.PlainCert); BouncyCastleX509Certificate serverCertificate = new X509CertificateParser().ReadCertificate(serverCertBytes); // Hash the salt and pin and use it to generate an AES key. byte[] hashedSaltAndPin = HashData(hashAlgorithm, saltAndPin); ICipherParameters aesKey = GenerateCipherKey(hashedSaltAndPin); // Generate a random challenge and encrypt it using AES. byte[] challenge = GenerateRandomBytes(16); byte[] encryptedChallenge = DoAesCipher(true, aesKey, challenge); await Task.Delay(2000); // Send the encrypted challenge to the server. // TODO: Call should have a timeout. uriString = string.Format( "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&clientchallenge={3}", ipAddress, BytesToHex(uniqueId), Guid.NewGuid().ToString("N"), BytesToHex(encryptedChallenge)); using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString))) { using (HttpResponseMessage response = await httpClient.SendRequestAsync(request)) { outputTextBox.Text = $"Send challenge status code: {response.StatusCode}\n"; string responseContent = await response.Content.ReadAsStringAsync(); outputTextBox.Text += responseContent + "\n"; using (StringReader reader = new StringReader(responseContent)) { XmlSerializer serializer = new XmlSerializer(typeof(PairResponse)); pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse; } } } if (pairResponse == null || pairResponse.Paired != 1) { outputTextBox.Text += "Pairing failed.\n"; return; } // Decode the server's response and subsequent challenge. byte[] encryptedServerChallengeResponse = HexToBytes(pairResponse.ChallengeResponse); byte[] decryptedServerChallengeResponse = DoAesCipher(false, aesKey, encryptedServerChallengeResponse); byte[] serverResponse = new byte[hashDigestSize]; byte[] serverChallenge = new byte[16]; Array.Copy(decryptedServerChallengeResponse, serverResponse, hashDigestSize); Array.Copy(decryptedServerChallengeResponse, hashDigestSize, serverChallenge, 0, 16); // Using another 16 byte secret, compute a challenge response hash using the secret, // our certificate signature, and the challenge. byte[] clientSecret = GenerateRandomBytes(16); byte[] challengeResponseHash = HashData( hashAlgorithm, ConcatenateByteArrays(serverChallenge, certificate.GetSignature(), clientSecret)); byte[] encryptedChallengeResponse = DoAesCipher(true, aesKey, challengeResponseHash); await Task.Delay(2000); // Send the challenge response to the server. // TODO: Call should have a timeout. uriString = string.Format( "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&serverchallengeresp={3}", ipAddress, BytesToHex(uniqueId), Guid.NewGuid().ToString("N"), BytesToHex(encryptedChallengeResponse)); using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString))) { using (HttpResponseMessage response = await httpClient.SendRequestAsync(request)) { outputTextBox.Text = $"Send challenge response status code: {response.StatusCode}\n"; string responseContent = await response.Content.ReadAsStringAsync(); outputTextBox.Text += responseContent + "\n"; using (StringReader reader = new StringReader(responseContent)) { XmlSerializer serializer = new XmlSerializer(typeof(PairResponse)); pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse; } } } if (pairResponse == null || pairResponse.Paired != 1) { outputTextBox.Text += "Pairing failed.\n"; // TODO: Unpair here by calling http://<blah>/unpair?uniqueid={1}&uuid={2}. return; } // Get the server's signed secret. byte[] serverSecretResponse = HexToBytes(pairResponse.PairingSecret); byte[] serverSecret = new byte[16]; byte[] serverSignature = new byte[256]; Array.Copy(serverSecretResponse, serverSecret, serverSecret.Length); Array.Copy(serverSecretResponse, serverSecret.Length, serverSignature, 0, serverSignature.Length); if (!VerifySignature(serverSecret, serverSignature, serverCertificate.GetPublicKey())) { outputTextBox.Text += "Pairing failed.\n"; // TODO: Unpair as above. return; } // Ensure the server challenge matched what we expected (the PIN was correct). byte[] serverChallengeResponseHash = HashData( hashAlgorithm, ConcatenateByteArrays( challenge, serverCertificate.GetSignature(), serverSecret)); if (!serverChallengeResponseHash.SequenceEqual(serverResponse)) { outputTextBox.Text += "Pairing failed due to wrong pin.\n"; // TODO: Unpair as above. return; } await Task.Delay(2000); // Send the server our signed secret // TODO: Call should have a timeout. byte[] signedSecret = SignData(clientSecret, keyPair.Private); byte[] clientPairingSecret = ConcatenateByteArrays( clientSecret, signedSecret); uriString = string.Format( "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&clientpairingsecret={3}", ipAddress, BytesToHex(uniqueId), Guid.NewGuid().ToString("N"), BytesToHex(clientPairingSecret)); using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString))) { using (HttpResponseMessage response = await httpClient.SendRequestAsync(request)) { outputTextBox.Text = $"Send client pairing secret status code: {response.StatusCode}\n"; string responseContent = await response.Content.ReadAsStringAsync(); outputTextBox.Text += responseContent + "\n"; using (StringReader reader = new StringReader(responseContent)) { XmlSerializer serializer = new XmlSerializer(typeof(PairResponse)); pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse; } } } if (pairResponse == null || pairResponse.Paired != 1) { outputTextBox.Text += "Pairing failed.\n"; // TODO: Unpair as above. return; } await Task.Delay(2000); // Do the initial challenge (seems neccessary for us to show as paired). // TODO: Call should have a timeout. uriString = string.Format( "https://{0}:47984/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&phrase=pairchallenge", ipAddress, BytesToHex(uniqueId), Guid.NewGuid().ToString("N")); using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString))) { using (HttpResponseMessage response = await httpClient.SendRequestAsync(request)) { outputTextBox.Text = $"Send pair challenge status code: {response.StatusCode}\n"; string responseContent = await response.Content.ReadAsStringAsync(); outputTextBox.Text += responseContent + "\n"; using (StringReader reader = new StringReader(responseContent)) { XmlSerializer serializer = new XmlSerializer(typeof(PairResponse)); pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse; } } } if (pairResponse == null || pairResponse.Paired != 1) { outputTextBox.Text += "Pairing failed.\n"; // TODO: Unpair as above. return; } await Task.Delay(2000); outputTextBox.Text = "Pairing succeeded!\n"; }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } if (password == null) { throw new ArgumentNullException("password"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool unmarkedKey = false; bool wrongPkcs12Zero = false; if (bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); IList chain = Platform.CreateArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; if (oid.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets = ((Asn1OctetString)ci.Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // IDictionary attributes = Platform.CreateHashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { unmarkedKey = true; keys["unmarked"] = pkcs12Key; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else { #if !NETFX_CORE Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); #endif } } } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { EncryptedData d = EncryptedData.GetInstance(ci.Content); byte[] octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // IDictionary attributes = Platform.CreateHashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { PrivateKeyInfo privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue); IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); // // set the attributes on the key // string alias = null; Asn1OctetString localId = null; IDictionary attributes = Platform.CreateHashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { #if !NETFX_CORE Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); #endif } } } else { #if !NETFX_CORE Console.WriteLine("extra " + oid); Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content)); #endif } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in chain) { CertBag cb = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)cb.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // IDictionary attributes = Platform.CreateHashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes); chainCerts[certId] = pkcs12Cert; if (unmarkedKey) { if (keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); keyCerts[name] = pkcs12Cert; object temp = keys["unmarked"]; keys.Remove("unmarked"); keys[name] = temp; } } else { if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); keyCerts[name] = pkcs12Cert; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = pkcs12Cert; } } } }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool wrongPkcs12Zero = false; if (password != null && bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); unmarkedKeyEntry = null; IList certBags = Platform.CreateArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; byte[] octets = null; if (oid.Equals(PkcsObjectIdentifiers.Data)) { octets = ((Asn1OctetString)ci.Content).GetOctets(); } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { if (password != null) { EncryptedData d = EncryptedData.GetInstance(ci.Content); octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); } } else { // TODO Other data types } if (octets != null) { Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { certBags.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes, password, wrongPkcs12Zero); } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes); } else { // TODO Other bag types } } } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in certBags) { CertBag certBag = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)certBag.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // IDictionary attributes = Platform.CreateHashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]); Asn1Set attrSet = Asn1Set.GetInstance(sq[1]); if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes); chainCerts[certId] = certEntry; if (unmarkedKeyEntry != null) { if (keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); keyCerts[name] = certEntry; keys[name] = unmarkedKeyEntry; } } else { if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); keyCerts[name] = certEntry; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = certEntry; } } } }
public Pkcs12Store( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } if (password == null) { throw new ArgumentNullException("password"); } Asn1InputStream bIn = new Asn1InputStream(input); Asn1Sequence obj = (Asn1Sequence)bIn.ReadObject(); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; ArrayList chain = new ArrayList(); bool unmarkedKey = false; bool wrongPkcs12Zero = false; if (bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters( algId.ObjectID, salt, itCount); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, parameters); IMac mac = (IMac)PbeUtilities.CreateEngine(algId.ObjectID); mac.Init(keyParameters); mac.BlockUpdate(data, 0, data.Length); byte[] res = new byte[mac.GetMacSize()]; mac.DoFinal(res, 0); byte[] dig = dInfo.GetDigest(); if (!Arrays.AreEqual(res, dig)) { if (password.Length > 0) { throw new Exception("Pkcs12 key store mac invalid - wrong password or corrupted file."); } // // may be incorrect zero length password // keyParameters = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, true, parameters); mac.Init(keyParameters); mac.BlockUpdate(data, 0, data.Length); res = new byte[mac.GetMacSize()]; mac.DoFinal(res, 0); if (!Arrays.AreEqual(res, dig)) { throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys = new Hashtable(); localIds = new Hashtable(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] c = authSafe.GetContentInfo(); for (int i = 0; i != c.Length; i++) { if (c[i].ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets = ((Asn1OctetString)c[i].Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); for (int j = 0; j != seq.Count; j++) { SafeBag b = new SafeBag((Asn1Sequence)seq[j]); if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { attr = attrSet[0]; attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } if (localId != null) { string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets())); if (alias == null) { keys[name] = pkcs12Key; } else { localIds[alias] = name; } } else { unmarkedKey = true; keys["unmarked"] = pkcs12Key; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else if (c[i].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData)) { EncryptedData d = EncryptedData.GetInstance(c[i].Content); Asn1Sequence seq = DecryptData(d.EncryptionAlgorithm, d.Content.GetOctets(), password, wrongPkcs12Zero); for (int j = 0; j != seq.Count; j++) { SafeBag b = new SafeBag((Asn1Sequence)seq[j]); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { attr = attrSet[0]; attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets())); if (alias == null) { keys[name] = pkcs12Key; } else { localIds[alias] = name; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { PrivateKeyInfo privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); // // set the attributes on the key // string alias = null; Asn1OctetString localId = null; Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { attr = attrSet[0]; attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets())); if (alias == null) { keys[name] = pkcs12Key; } else { localIds[alias] = name; } } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else { Console.WriteLine("extra " + c[i].ContentType.Id); Console.WriteLine("extra " + Asn1Dump.DumpAsString(c[i].Content)); } } } certs = new Hashtable(); chainCerts = new Hashtable(); keyCerts = new Hashtable(); for (int i = 0; i < chain.Count; ++i) { SafeBag b = (SafeBag)chain[i]; CertBag cb = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)cb.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // Hashtable attributes = new Hashtable(); X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; if (attrSet.Count > 0) { Asn1Encodable attr = attrSet[0]; attributes.Add(aOid.Id, attr); if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } AsymmetricKeyParameter publicKey = cert.GetPublicKey(); chainCerts[new CertId(publicKey)] = pkcs12Cert; if (unmarkedKey) { if (keyCerts.Count == 0) { string name = Encoding.ASCII.GetString( Hex.Encode( new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)).GetKeyIdentifier())); keyCerts[name] = pkcs12Cert; object temp = keys["unmarked"]; keys.Remove("unmarked"); keys[name] = temp; } } else { if (localId != null) { string name = Encoding.ASCII.GetString( Hex.Encode(localId.GetOctets())); keyCerts[name] = pkcs12Cert; } if (alias != null) { certs[alias] = pkcs12Cert; } } } }
private byte[] GetPublicKey(X509Certificate2 certificate) { var rootBCCert = new X509CertificateParser().ReadCertificate(certificate.RawData); return(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootBCCert.GetPublicKey()).GetDerEncoded()); }
private static AsymmetricKeyParameter GetAsymmetricKeyParameterWithX509(byte[] x509CertData) { var certificate = new X509CertificateParser().ReadCertificate(x509CertData); return(certificate.GetPublicKey()); }