/// <summary> /// Encodes the public key into DER encoding. /// </summary> /// <param name="key">The public key.</param> /// <returns>The encoded public key.</returns> public static string ToPublicKeyString(AsymmetricKeyParameter key) { return(Convert.ToBase64String(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key).ToAsn1Object().GetDerEncoded())); }
private void DoTestECDH(string algorithm) { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm); X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // a side // AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(algorithm + " 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algorithm); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc); ECDomainParameters ecDP = pubKey.Parameters; // if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW())) ECPoint pq1 = pubKey.Q.Normalize(), pq2 = ((ECPublicKeyParameters)aKeyPair.Public).Q.Normalize(); if (!pq1.Equals(pq2)) { // Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX()); // Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY()); // Fail(algorithm + " public key encoding (W test) failed"); Console.WriteLine(" expected " + pq1.AffineXCoord.ToBigInteger() + " got " + pq2.AffineXCoord.ToBigInteger()); Console.WriteLine(" expected " + pq1.AffineYCoord.ToBigInteger() + " got " + pq2.AffineYCoord.ToBigInteger()); Fail(algorithm + " public key encoding (Q test) failed"); } // if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator())) if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G)) { Fail(algorithm + " public key encoding (G test) failed"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D)) { // Fail(algorithm + " private key encoding (S test) failed"); Fail(algorithm + " private key encoding (D test) failed"); } // if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator())) if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G)) { Fail(algorithm + " private key encoding (G test) failed"); } }
// Only the ctor should be calling with isAuthority = true // if isAuthority, value for isMachineCert doesn't matter private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings) { if (certificateCreationSettings == null) { if (isAuthority) { certificateCreationSettings = new CertificateCreationSettings(); } else { throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false"); } } // Set to default cert creation settings if not set if (certificateCreationSettings.ValidityNotBefore == default(DateTime)) { certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore; } if (certificateCreationSettings.ValidityNotAfter == default(DateTime)) { certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter; } if (!isAuthority ^ (signingCertificate != null)) { throw new ArgumentException("Either isAuthority == true or signingCertificate is not null"); } string subject = certificateCreationSettings.Subject; // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject // so that the default certificate generated is compatible with mainline scenarios // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out if (certificateCreationSettings.SubjectAlternativeNames == null) { certificateCreationSettings.SubjectAlternativeNames = new string[1] { subject }; } string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames; if (!isAuthority && string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject"); } EnsureInitialized(); _certGenerator.Reset(); _certGenerator.SetSignatureAlgorithm(_signatureAlthorithm); X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName); var serialNum = new BigInteger(64 /*sizeInBits*/, _random).Abs(); var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair(); if (isAuthority) { _certGenerator.SetIssuerDN(authorityX509Name); _certGenerator.SetSubjectDN(authorityX509Name); var authorityKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public), new GeneralNames(new GeneralName(authorityX509Name)), serialNum); _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); _certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign)); } else { X509Name subjectName = CreateX509Name(subject); _certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate)); _certGenerator.SetSubjectDN(subjectName); _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public)); _certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment)); } _certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public)); _certGenerator.SetSerialNumber(serialNum); _certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore); _certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter); _certGenerator.SetPublicKey(keyPair.Public); _certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority)); _certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth)); if (!isAuthority) { if (isMachineCert) { List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>(); // All endpoints should also be in the Subject Alt Names for (int i = 0; i < subjectAlternativeNames.Length; i++) { if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i])) { // Machine certs can have additional DNS names subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i])); } } _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray())); } else { if (subjectAlternativeNames.Length > 1) { var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector(); // Only add a SAN for the user if there are any for (int i = 1; i < subjectAlternativeNames.Length; i++) { if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i])) { Asn1EncodableVector otherNames = new Asn1EncodableVector(); otherNames.Add(new DerObjectIdentifier(_upnObjectId)); otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i]))); Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames)); subjectAlternativeNamesAsAsn1EncodableList.Add(genName); } } _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList)); } } } // Our CRL Distribution Point has the serial number in the query string to fool Windows into doing a fresh query // rather than using a cached copy of the CRL in the case where the CRL has been previously accessed before var crlDistributionPoints = new DistributionPoint[2] { new DistributionPoint(new DistributionPointName( new GeneralNames(new GeneralName( GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))), null, null), new DistributionPoint(new DistributionPointName( new GeneralNames(new GeneralName( GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))), null, new GeneralNames(new GeneralName(authorityX509Name))) }; var revocationListExtension = new CrlDistPoint(crlDistributionPoints); _certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension); X509Certificate cert = _certGenerator.Generate(_authorityKeyPair.Private, _random); switch (certificateCreationSettings.ValidityType) { case CertificateValidityType.Revoked: RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16)); break; case CertificateValidityType.Expired: break; default: EnsureCertificateIsValid(cert); break; } // For now, given that we don't know what format to return it in, preserve the formats so we have // the flexibility to do what we need to X509CertificateContainer container = new X509CertificateContainer(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; chain[0] = new X509CertificateEntry(cert); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry( certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty, new AsymmetricKeyEntry(keyPair.Private), chain); using (MemoryStream stream = new MemoryStream()) { store.Save(stream, _password.ToCharArray(), _random); container.Pfx = stream.ToArray(); } X509Certificate2 outputCert; if (isAuthority) { // don't hand out the private key for the cert when it's the authority outputCert = new X509Certificate2(cert.GetEncoded()); } else { // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key // you will have to re-export this cert if needed outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); } container.Subject = subject; container.InternalCertificate = cert; container.Certificate = outputCert; container.Thumbprint = outputCert.Thumbprint; Trace.WriteLine("[CertificateGenerator] generated a certificate:"); Trace.WriteLine(string.Format(" {0} = {1}", "isAuthority", isAuthority)); if (!isAuthority) { Trace.WriteLine(string.Format(" {0} = {1}", "Signed by", signingCertificate.SubjectDN)); Trace.WriteLine(string.Format(" {0} = {1}", "Subject (CN) ", subject)); Trace.WriteLine(string.Format(" {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames))); Trace.WriteLine(string.Format(" {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName)); } Trace.WriteLine(string.Format(" {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey)); Trace.WriteLine(string.Format(" {0} = {1}", "Thumbprint", outputCert.Thumbprint)); Trace.WriteLine(string.Format(" {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType)); return(container); }
public SimpleTestResult EncodeRecodePublicKey() { DerObjectIdentifier oid = ECGost3410NamedCurves.GetOid("Tc26-Gost-3410-12-512-paramSetA"); ECNamedDomainParameters ecp = new ECNamedDomainParameters(oid, ECGost3410NamedCurves.GetByOidX9(oid)); ECGost3410Parameters gostParams = new ECGost3410Parameters(ecp, oid, RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512, null); ECKeyGenerationParameters paramameters = new ECKeyGenerationParameters(gostParams, new SecureRandom()); ECKeyPairGenerator engine = new ECKeyPairGenerator(); engine.Init(paramameters); AsymmetricCipherKeyPair pair = engine.GenerateKeyPair(); ECPublicKeyParameters generatedKeyParameters = (ECPublicKeyParameters)pair.Public; ECPublicKeyParameters keyParameters = generatedKeyParameters; // // Continuously encode/decode the key and check for loss of information. // for (int t = 0; t < 3; t++) { SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyParameters); keyParameters = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(info); { // Specifically cast and test gost parameters. ECGost3410Parameters gParam = (ECGost3410Parameters)generatedKeyParameters.Parameters; ECGost3410Parameters rParam = (ECGost3410Parameters)keyParameters.Parameters; bool ok = SafeEquals(gParam.DigestParamSet, rParam.DigestParamSet) && SafeEquals(gParam.EncryptionParamSet, rParam.EncryptionParamSet) && SafeEquals(gParam.PublicKeyParamSet, rParam.PublicKeyParamSet); if (!ok) { return(new SimpleTestResult(false, "GOST parameters does not match")); } } if (!((ECGost3410Parameters)keyParameters.Parameters).Name.Equals( ((ECGost3410Parameters)generatedKeyParameters.Parameters).Name)) { return(new SimpleTestResult(false, "Name does not match")); } if (keyParameters.IsPrivate != generatedKeyParameters.IsPrivate) { return(new SimpleTestResult(false, "isPrivate does not match")); } if (!Arrays.AreEqual(keyParameters.Q.GetEncoded(true), generatedKeyParameters.Q.GetEncoded(true))) { return(new SimpleTestResult(false, "Q does not match")); } if (!keyParameters.Parameters.Curve.Equals(generatedKeyParameters.Parameters.Curve)) { return(new SimpleTestResult(false, "Curve does not match")); } if (!Arrays.AreEqual( keyParameters.Parameters.G.GetEncoded(true), generatedKeyParameters.Parameters.G.GetEncoded(true))) { return(new SimpleTestResult(false, "G does not match")); } if (!keyParameters.Parameters.H.Equals(generatedKeyParameters.Parameters.H)) { return(new SimpleTestResult(false, "H does not match")); } if (!keyParameters.Parameters.HInv.Equals(generatedKeyParameters.Parameters.HInv)) { return(new SimpleTestResult(false, "Hinv does not match")); } if (!keyParameters.Parameters.N.Equals(generatedKeyParameters.Parameters.N)) { return(new SimpleTestResult(false, "N does not match")); } if (!Arrays.AreEqual(keyParameters.Parameters.GetSeed(), generatedKeyParameters.Parameters.GetSeed())) { return(new SimpleTestResult(false, "Seed does not match")); } } return(new SimpleTestResult(true, null)); }
/// <summary> /// 生成X509 V3证书 /// </summary> /// <param name="certPath">Cert证书路径</param> /// <param name="endDate">证书失效时间</param> /// <param name="keySize">密钥长度</param> /// <param name="password">证书密码</param> /// <param name="signatureAlgorithm">设置将用于签署此证书的签名算法</param> /// <param name="issuer">设置此证书颁发者的DN</param> /// <param name="subject">设置此证书使用者的DN</param> /// <param name="pfxPath">Pfx证书路径</param> /// <param name="friendlyName">设置证书友好名称(可选)</param> /// <param name="startDate">证书生效时间</param> /// <param name="algorithm">加密算法</param> public static void X509V3(string algorithm, int keySize, string password, string signatureAlgorithm, DateTime startDate, DateTime endDate, X509Name issuer, X509Name subject, string certPath, string pfxPath, string friendlyName = "") { //generate Random Numbers CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); var keyGenerator = GeneratorUtilities.GetKeyPairGenerator(algorithm); keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); var keyPair = keyGenerator.GenerateKeyPair(); var v3CertGen = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); v3CertGen.SetSerialNumber(serialNumber); //设置证书的序列号 v3CertGen.SetIssuerDN(issuer); //设置颁发者信息 v3CertGen.SetSubjectDN(subject); //设置使用者信息 v3CertGen.SetNotBefore(startDate); //设置证书的生效日期 v3CertGen.SetNotAfter(endDate); //设置证书失效的日期 v3CertGen.SetPublicKey(keyPair.Public); //设置此证书的公钥 ISignatureFactory sigFact = new Asn1SignatureFactory(signatureAlgorithm, keyPair.Private); //签名算法&设置此证书的私钥 var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); //设置一些扩展字段 //基本约束 v3CertGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); //使用者密钥标识符 v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki)); //授权密钥标识符 v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(spki)); var x509Certificate = v3CertGen.Generate(sigFact); //生成证书 x509Certificate.CheckValidity(); //检查当前日期是否在证书的有效期内 x509Certificate.Verify(keyPair.Public); //使用公钥验证证书的签名 var certificate2 = new X509Certificate2(DotNetUtilities.ToX509Certificate(x509Certificate)) { FriendlyName = friendlyName, //设置友好名称 }; //cer公钥文件 var bytes = certificate2.Export(X509ContentType.Cert); using (var fs = new FileStream(certPath, FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); } //pfx证书,包含公钥私钥 //CopyWithPrivateKey netstandard2.1支持 certificate2 = certificate2.CopyWithPrivateKey(DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private)); var bytes2 = certificate2.Export(X509ContentType.Pfx, password); using (var fs = new FileStream(pfxPath, FileMode.Create)) { fs.Write(bytes2, 0, bytes2.Length); } var a = certificate2.GetRawCertDataString(); var b = Hex.Encode(certificate2.RawData); X509Certificate2 x2 = new X509Certificate2(Hex.Decode(b), "123456"); var c = a; //如果使用 netstandard2.0 请使用下面的代码 #if NETSTANDARD2_0 var certEntry = new X509CertificateEntry(x509Certificate); var store = new Pkcs12StoreBuilder().Build(); store.SetCertificateEntry(friendlyName, certEntry); //设置证书 var chain = new X509CertificateEntry[1]; chain[0] = certEntry; store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), chain); //设置私钥 using (var fs = File.Create(pfxPath)) { store.Save(fs, password.ToCharArray(), new SecureRandom()); //保存 } #endif }
public static byte[] PublicKeyToByteArray(this AsymmetricCipherKeyPair keyPair) { var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); return(publicKeyInfo.ToAsn1Object().GetDerEncoded()); }
public static byte[] GetDerEncodedPublicKey(AsymmetricCipherKeyPair keypair) { return(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public).GetDerEncoded()); }
/// <summary> /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials. /// </summary> ///<param name="signatureAlgorithm">Name of Sig Alg.</param> /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param> /// <param name="publicKey">Public Key to be included in cert reqest.</param> /// <param name="attributes">ASN1Set of Attributes.</param> /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param> public Pkcs10CertificationRequest( string signatureAlgorithm, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey) { if (signatureAlgorithm == null) { throw new ArgumentNullException("signatureAlgorithm"); } if (subject == null) { throw new ArgumentNullException("subject"); } if (publicKey == null) { throw new ArgumentNullException("publicKey"); } if (publicKey.IsPrivate) { throw new ArgumentException("expected public key", "publicKey"); } if (!signingKey.IsPrivate) { throw new ArgumentException("key for signing must be private", "signingKey"); } // DerObjectIdentifier sigOid = SignerUtilities.GetObjectIdentifier(signatureAlgorithm); string algorithmName = signatureAlgorithm.ToUpper(CultureInfo.InvariantCulture); DerObjectIdentifier sigOid = (DerObjectIdentifier)algorithms[algorithmName]; if (sigOid == null) { throw new ArgumentException("Unknown signature type requested"); } if (noParams.Contains(sigOid)) { this.sigAlgId = new AlgorithmIdentifier(sigOid); } else if (exParams.ContainsKey(algorithmName)) { this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable)exParams[algorithmName]); } else { this.sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance); } SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes); ISigner sig = SignerUtilities.GetSigner(signatureAlgorithm); sig.Init(true, signingKey); try { // Encode. byte[] b = reqInfo.GetDerEncoded(); sig.BlockUpdate(b, 0, b.Length); } catch (Exception e) { throw new ArgumentException("exception encoding TBS cert request", e); } // Generate Signature. sigBits = new DerBitString(sig.GenerateSignature()); }
public SelfCertificateDialog(IServiceProvider serviceProvider, CertificatesFeature feature) : base(serviceProvider) { InitializeComponent(); cbStore.SelectedIndex = 0; cbLength.SelectedIndex = 3; cbHashing.SelectedIndex = 1; txtCommonName.Text = Environment.MachineName; dtpFrom.Value = DateTime.Now; dtpTo.Value = dtpFrom.Value.AddYears(1); if (Environment.OSVersion.Version < Version.Parse("6.2")) { // IMPORTANT: WebHosting store is available since Windows 8. cbStore.Enabled = false; } if (!Helper.IsRunningOnMono()) { NativeMethods.TryAddShieldToButton(btnOK); } var container = new CompositeDisposable(); FormClosed += (sender, args) => container.Dispose(); container.Add( Observable.FromEventPattern <EventArgs>(txtName, "TextChanged") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text); })); container.Add( Observable.FromEventPattern <EventArgs>(btnOK, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { var names = txtCommonName.Text; if (string.IsNullOrWhiteSpace(names)) { ShowMessage("DNS names cannot be empty.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } var dnsNames = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(item => item.Trim()).ToArray(); if (dnsNames.Length == 0) { ShowMessage("DNS names cannot be empty.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } // Generate certificate string defaultIssuer = string.Format("CN={0}", dnsNames[0]); string defaultSubject = defaultIssuer; string subject = defaultSubject; string issuer = defaultIssuer; if (subject == null) { throw new Exception("Missing Subject Name"); } DateTime notBefore = dtpFrom.Value; DateTime notAfter = dtpTo.Value; var random = new SecureRandom(new CryptoApiRandomGenerator()); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, int.Parse(cbLength.Text))); var cerKp = kpgen.GenerateKeyPair(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certGen.SetSerialNumber(serialNumber); certGen.SetIssuerDN(new X509Name(issuer)); certGen.SetNotBefore(notBefore); certGen.SetNotAfter(notAfter); if (dnsNames.Length == 1) { certGen.SetSubjectDN(new X509Name(subject)); } certGen.SetPublicKey(cerKp.Public); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); var keyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cerKp.Public); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, true, new SubjectKeyIdentifier(keyInfo)); certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(keyInfo)); certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)); if (cbGenerate.Checked) { var subjectAlternativeNames = new List <Asn1Encodable>(); foreach (var item in dnsNames) { subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, item)); } var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames.ToArray()); certGen.AddExtension(X509Extensions.SubjectAlternativeName, true, subjectAlternativeNamesExtension); } string hashName = cbHashing.SelectedIndex == 0 ? "SHA1WithRSA" : "SHA256WithRSA"; var factory = new Asn1SignatureFactory(hashName, cerKp.Private, random); string p12File = Path.GetTempFileName(); string p12pwd = "test"; try { Org.BouncyCastle.X509.X509Certificate x509 = certGen.Generate(factory); var store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(x509); var friendlyName = txtName.Text; store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(cerKp.Private), new[] { certificateEntry }); var stream = new MemoryStream(); store.Save(stream, p12pwd.ToCharArray(), random); File.WriteAllBytes(p12File, stream.ToArray()); Item = new X509Certificate2(p12File, p12pwd) { FriendlyName = friendlyName }; Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting"; try { using var process = new Process(); // add certificate var start = process.StartInfo; start.Verb = "runas"; start.UseShellExecute = true; start.FileName = "cmd"; start.Arguments = $"/c \"\"{CertificateInstallerLocator.FileName}\" /f:\"{p12File}\" /p:{p12pwd} /n:\"{txtName.Text}\" /s:{(cbStore.SelectedIndex == 0 ? "MY" : "WebHosting")}\""; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); File.Delete(p12File); if (process.ExitCode == 0) { DialogResult = DialogResult.OK; } else { ShowMessage(process.ExitCode.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } } catch (Win32Exception ex) { // elevation is cancelled. if (!Microsoft.Web.Administration.NativeMethods.ErrorCancelled(ex.NativeErrorCode)) { RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { RollbarLocator.RollbarInstance.Error(ex); } } catch (Exception ex) { RollbarLocator.RollbarInstance.Error(ex); ShowError(ex, Text, false); return; } })); container.Add( Observable.FromEventPattern <CancelEventArgs>(this, "HelpButtonClicked") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(EnvironmentVariableTarget => { feature.ShowHelp(); })); }
public async Task <bool> RequestMinecraftChain(AuthResponse <XuiDisplayClaims <XstsXui> > token, AsymmetricCipherKeyPair key) { var b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(MinecraftKeyPair.Public).GetEncoded().EncodeBase64(); var body = new MCChainPostData() { IdentityPublicKey = b }; var client = GetClient(); //using (var client = new HttpClient()) { using (var r = new HttpRequestMessage(HttpMethod.Post, MinecraftAuthUrl)) { //r.Headers.Add("x-xbl-contract-version", "1"); r.Content = SetHttpContent(body, out var jsonData); r.Headers.Add("Authorization", $"XBL3.0 x={token.DisplayClaims.Xui[0].Uhs};{token.Token}"); r.Headers.Add("User-Agent", "MCPE/UWP"); r.Headers.Add("Client-Version", McpeProtocolInfo.ProtocolVersion.ToString()); //Sign(r, jsonData); try { using (var response = await client .SendAsync(r, HttpCompletionOption.ResponseContentRead) .ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); var rawResponse = await response.Content.ReadAsStringAsync(); DecodedChain = new ChainData(); dynamic a = JObject.Parse(rawResponse); var chain = ((JArray)a.chain).Values <string>().ToArray(); DecodedChain.Chain = new CertificateData[chain.Length]; for (int i = 0; i < chain.Length; i++) { var element = chain[i]; try { DecodedChain.Chain[i] = JWT.Payload <CertificateData>(element); } catch (Exception ex) { Log.Error($"Could not parse chain element: {ex.ToString()}"); } } //DecodedChain = JsonConvert.DeserializeObject<ChainData>(rawResponse); MinecraftChain = Encoding.UTF8.GetBytes(rawResponse); // //Log.Debug($"Chain: {rawResponse}"); } } catch (Exception ex) { Log.Warn($"AHHH: {ex.ToString()}"); return(false); } } } // //Log.Debug($"Xbox login processed!"); return(true); }
public string CreateNewCertificate(string subjectName, string pvkPass, X509Certificate2 issuer, string path = @".\certs\") { var generator = new X509V3CertificateGenerator(); // Generate pseudo random number var randomGen = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGen); // Set certificate serial number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); generator.SetSerialNumber(serialNumber); // Set certificate subject name var subjectDN = new X509Name($"CN={subjectName}"); generator.SetSubjectDN(subjectDN); // Set issuer subject name var issuerDN = new X509Name(issuer.Subject); generator.SetIssuerDN(issuerDN); // Set certificate validity var notBefore = DateTime.UtcNow.Date; generator.SetNotBefore(notBefore); generator.SetNotAfter(notBefore.AddYears(2)); // Generate new RSA key pair for certificate var keyGeneratorParameters = new KeyGenerationParameters(random, RSAKeyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGeneratorParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); // Import public key into generator generator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey); // Get key pair from .net issuer certificate //var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey); var issuerSerialNumber = new BigInteger(issuer.GetSerialNumber()); // Sign CA key with serial var caKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber); generator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, caKeyIdentifier); // Create signature factory to sign new cert ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerKeyPair.Private); // Generate new bouncy castle certificate signed by issuer var newCertificate = generator.Generate(signatureFactory); var store = new Pkcs12Store(); var friendlyName = newCertificate.SubjectDN.ToString().Split('=')[1]; var certificateEntry = new X509CertificateEntry(newCertificate); // Set certificate store.SetCertificateEntry(friendlyName, certificateEntry); // Set private key store.SetKeyEntry( friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); var privatePath = path + $"{friendlyName}.pfx"; var publicPath = path + $"{friendlyName}.cer"; using (var stream = new MemoryStream()) { // Convert bouncy castle cert => .net cert store.Save(stream, pvkPass.ToCharArray(), random); var dotNetCertificate = new X509Certificate2( stream.ToArray(), pvkPass, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Extract public part to store in server storage var publicCert = dotNetCertificate.Export(X509ContentType.Cert); // Extract private parameters to export into .pfx for distribution var privateCert = dotNetCertificate.Export(X509ContentType.Pfx, pvkPass); dotNetCertificate.Dispose(); // Write private parameters to .pfx file to install at client File.WriteAllBytes(privatePath, privateCert); File.WriteAllBytes(publicPath, publicCert); } return(privatePath); }
public override X509CertificateBuilderResult Build() { var issuerX509Certificate2 = new SystemX509Certificates.X509Certificate2( IssuerCertificate, IssuerCertificatePassword, SystemX509Certificates.X509KeyStorageFlags.Exportable ); var issuerSubjectDN = issuerX509Certificate2.ToX509Certificate().SubjectDN; X509V3CertificateGenerator.SetIssuerDN(issuerSubjectDN); // Generate Keys. var rsaKeyPairGenerator = new RsaKeyPairGenerator(); rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), this.KeySize)); var asymmetricCipherKeyPair = rsaKeyPairGenerator.GenerateKeyPair(); // Set Public Key. X509V3CertificateGenerator.SetPublicKey(asymmetricCipherKeyPair.Public); // Key Usage - for maximum interoperability, specify all four flags. var keyUsage = KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment | KeyUsage.KeyAgreement; X509V3CertificateGenerator.AddExtension( X509Extensions.KeyUsage, true, new KeyUsage(keyUsage) ); X509V3CertificateGenerator.AddExtension( X509Extensions.BasicConstraints, true, new BasicConstraints(false) ); // Extended Key Usage. var extendedKeyUsage = new List <KeyPurposeID>(); // Set TLS Web Server Authentication (1.3.6.1.5.5.7.3.1). if (IsServerAuthKeyUsage) { extendedKeyUsage.Add(KeyPurposeID.IdKPServerAuth); } // Set TLS Web Client Authentication (1.3.6.1.5.5.7.3.2). if (IsClientAuthKeyUsage) { extendedKeyUsage.Add(KeyPurposeID.IdKPClientAuth); } X509V3CertificateGenerator.AddExtension( X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(extendedKeyUsage) ); // Set Subject Alternative Names. if (SubjectAlternativeNames != null) { var subjectAlternativeNames = new Asn1Encodable[SubjectAlternativeNames.Count]; for (int i = 0; i < SubjectAlternativeNames.Count; i++) { subjectAlternativeNames[i] = new GeneralName(GeneralName.DnsName, SubjectAlternativeNames[i]); } X509V3CertificateGenerator.AddExtension( X509Extensions.SubjectAlternativeName, false, new DerSequence(subjectAlternativeNames) ); } X509V3CertificateGenerator.AddExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerX509Certificate2.GetPublicKeyAsAsymmetricKeyParameter()), new GeneralNames(new GeneralName(issuerSubjectDN)), new Org.BouncyCastle.Math.BigInteger(issuerX509Certificate2.GetSerialNumber()) ) ); X509V3CertificateGenerator.AddExtension( X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricCipherKeyPair.Public) ) ); var signatureFactory = new Asn1SignatureFactory(GetSignatureAlgorithm(this.KeySize), issuerX509Certificate2.GetPrivateKeyAsAsymmetricKeyParameter()); // Generate X.509 Certificate. var x509Certificate = X509V3CertificateGenerator.Generate(signatureFactory); return(new X509CertificateBuilderResult(x509Certificate, asymmetricCipherKeyPair.Private)); }
private void generationTest() { byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ISigner s = SignerUtilities.GetSigner("GOST3410"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410"); g.Init( new Gost3410KeyGenerationParameters( new SecureRandom(), CryptoProObjectIdentifiers.GostR3410x94CryptoProA)); AsymmetricCipherKeyPair p = g.GenerateKeyPair(); AsymmetricKeyParameter sKey = p.Private; AsymmetricKeyParameter vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("GOST3410"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("GOST3410 verification failed"); } // // default initialisation test // s = SignerUtilities.GetSigner("GOST3410"); g = GeneratorUtilities.GetKeyPairGenerator("GOST3410"); // TODO This is supposed to be a 'default initialisation' test, but don't have a factory // These values are defaults from JCE provider g.Init( new Gost3410KeyGenerationParameters( new SecureRandom(), CryptoProObjectIdentifiers.GostR3410x94CryptoProA)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("GOST3410"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("GOST3410 verification failed"); } // // encoded test // //KeyFactory f = KeyFactory.getInstance("GOST3410"); //X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.GetEncoded()); //Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s); byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded(); Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters) PublicKeyFactory.CreateKey(vKeyEnc); if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y)) { Fail("public number not decoded properly"); } //PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded()); //Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8); byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded(); Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters) PrivateKeyFactory.CreateKey(sKeyEnc); if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X)) { Fail("private number not decoded properly"); } // // ECGOST3410 generation test // s = SignerUtilities.GetSigner("ECGOST3410"); g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p ECCurve curve = new FpCurve( mod_p, // p new BigInteger("7"), // a new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("2"), new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280"), false), new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECGOST3410"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECGOST3410 verification failed"); } }
private static byte[] SerializePublicKey(AsymmetricKeyParameter publicKey) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(SerializeKey(publicKeyInfo)); }
private (X509Certificate _serverCertificate, RsaKeyParameters _serverKey) GenerateCertificate(ApplicationDescription applicationDescription) { if (applicationDescription == null) { throw new ArgumentNullException(nameof(applicationDescription)); } string applicationUri = applicationDescription.ApplicationUri; if (string.IsNullOrEmpty(applicationUri)) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } string subjectName = null; string hostName = null; UriBuilder appUri = new UriBuilder(applicationUri); if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host)) { var path = appUri.Path.Trim('/'); if (!string.IsNullOrEmpty(path)) { hostName = appUri.Host; var appName = path; subjectName = $"CN={appName},DC={hostName}"; } } if (appUri.Scheme == "urn") { var parts = appUri.Path.Split(new[] { ':' }, 2); if (parts.Length == 2) { hostName = parts[0]; var appName = parts[1]; subjectName = $"CN={appName},DC={hostName}"; } } if (subjectName == null) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } // Create new certificate var subjectDN = new X509Name(subjectName); // Create a keypair. RsaKeyPairGenerator kg = new RsaKeyPairGenerator(); kg.Init(new KeyGenerationParameters(_rng, 2048)); var kp = kg.GenerateKeyPair(); var key = kp.Private as RsaPrivateCrtKeyParameters; // Create a certificate. X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); var subjectSN = BigInteger.ProbablePrime(120, _rng); cg.SetSerialNumber(subjectSN); cg.SetSubjectDN(subjectDN); cg.SetIssuerDN(subjectDN); cg.SetNotBefore(DateTime.Now.Date.ToUniversalTime()); cg.SetNotAfter(DateTime.Now.Date.ToUniversalTime().AddYears(25)); cg.SetPublicKey(kp.Public); cg.AddExtension( X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); cg.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public))); cg.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN)); cg.AddExtension( X509Extensions.SubjectAlternativeName, false, new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) })); cg.AddExtension( X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment)); cg.AddExtension( X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth)); var crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, _rng)); return(crt, key); }
private void doTestParams( byte[] ecParameterEncoded, bool compress) { // string keyStorePass = "******"; Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(ecParameterEncoded); X9ECParameters x9 = new X9ECParameters(seq); IAsymmetricCipherKeyPair kp = null; bool success = false; while (!success) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); // kpg.Init(new ECParameterSpec(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed())); ECDomainParameters ecParams = new ECDomainParameters( x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); kpg.Init(new ECKeyGenerationParameters(ecParams, new SecureRandom())); kp = kpg.GenerateKeyPair(); // The very old Problem... we need a certificate chain to // save a private key... ECPublicKeyParameters pubKey = (ECPublicKeyParameters)kp.Public; if (!compress) { //pubKey.setPointFormat("UNCOMPRESSED"); pubKey = SetPublicUncompressed(pubKey, false); } byte[] x = pubKey.Q.X.ToBigInteger().ToByteArrayUnsigned(); byte[] y = pubKey.Q.Y.ToBigInteger().ToByteArrayUnsigned(); if (x.Length == y.Length) { success = true; } } // The very old Problem... we need a certificate chain to // save a private key... X509CertificateEntry[] chain = new X509CertificateEntry[] { new X509CertificateEntry(GenerateSelfSignedSoftECCert(kp, compress)) }; // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(null, keyStorePass.ToCharArray()); Pkcs12Store keyStore = new Pkcs12StoreBuilder().Build(); keyStore.SetCertificateEntry("ECCert", chain[0]); ECPrivateKeyParameters privateECKey = (ECPrivateKeyParameters)kp.Private; keyStore.SetKeyEntry("ECPrivKey", new AsymmetricKeyEntry(privateECKey), chain); // Test ec sign / verify ECPublicKeyParameters pub = (ECPublicKeyParameters)kp.Public; // string oldPrivateKey = new string(Hex.encode(privateECKey.getEncoded())); byte[] oldPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateECKey).GetDerEncoded(); string oldPrivateKey = Hex.ToHexString(oldPrivateKeyBytes); // string oldPublicKey = new string(Hex.encode(pub.getEncoded())); byte[] oldPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub).GetDerEncoded(); string oldPublicKey = Hex.ToHexString(oldPublicKeyBytes); ECPrivateKeyParameters newKey = (ECPrivateKeyParameters) keyStore.GetKey("ECPrivKey").Key; ECPublicKeyParameters newPubKey = (ECPublicKeyParameters) keyStore.GetCertificate("ECCert").Certificate.GetPublicKey(); if (!compress) { // TODO Private key compression? //newKey.setPointFormat("UNCOMPRESSED"); //newPubKey.setPointFormat("UNCOMPRESSED"); newPubKey = SetPublicUncompressed(newPubKey, false); } // string newPrivateKey = new string(Hex.encode(newKey.getEncoded())); byte[] newPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(newKey).GetDerEncoded(); string newPrivateKey = Hex.ToHexString(newPrivateKeyBytes); // string newPublicKey = new string(Hex.encode(newPubKey.getEncoded())); byte[] newPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newPubKey).GetDerEncoded(); string newPublicKey = Hex.ToHexString(newPublicKeyBytes); if (!oldPrivateKey.Equals(newPrivateKey)) // if (!privateECKey.Equals(newKey)) { Fail("failed private key comparison"); } if (!oldPublicKey.Equals(newPublicKey)) // if (!pub.Equals(newPubKey)) { Fail("failed public key comparison"); } }
private static SubjectKeyIdentifier CreateSubjectKeyID( AsymmetricKeyParameter pubKey) { return(new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey))); }
public static byte[] ToBytes(this AsymmetricKeyParameter key) { return(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key).GetDerEncoded()); }
private PemObject CreatePemObject(object o) { if (obj == null) { throw new ArgumentNullException("obj"); } if (obj is AsymmetricCipherKeyPair) { return(CreatePemObject(((AsymmetricCipherKeyPair)obj).Private)); } string type; byte[] encoding; if (o is PemObject) { return((PemObject)o); } if (o is PemObjectGenerator) { return(((PemObjectGenerator)o).Generate()); } if (obj is X509Certificate) { // TODO Should we prefer "X509 CERTIFICATE" here? type = "CERTIFICATE"; try { encoding = ((X509Certificate)obj).GetEncoded(); } catch (CertificateEncodingException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } else if (obj is X509Crl) { type = "X509 CRL"; try { encoding = ((X509Crl)obj).GetEncoded(); } catch (CrlException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } else if (obj is AsymmetricKeyParameter) { AsymmetricKeyParameter akp = (AsymmetricKeyParameter)obj; if (akp.IsPrivate) { string keyType; encoding = EncodePrivateKey(akp, out keyType); type = keyType + " PRIVATE KEY"; } else { type = "PUBLIC KEY"; encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded(); } } else if (obj is IX509AttributeCertificate) { type = "ATTRIBUTE CERTIFICATE"; encoding = ((X509V2AttributeCertificate)obj).GetEncoded(); } else if (obj is Pkcs10CertificationRequest) { type = "CERTIFICATE REQUEST"; encoding = ((Pkcs10CertificationRequest)obj).GetEncoded(); } else if (obj is Asn1.Cms.ContentInfo) { type = "PKCS7"; encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded(); } else { throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName); } return(new PemObject(type, encoding)); }
public static byte[] EncodeSkinJwt(AsymmetricCipherKeyPair newKey, string username) { var resourcePatch = new SkinResourcePatch() { Geometry = new GeometryIdentifier() { Default = "geometry.humanoid.customSlim" } }; var skin = new Skin { SkinId = $"{Guid.NewGuid().ToString()}.CustomSlim", SkinResourcePatch = resourcePatch, Slim = true, Height = 32, Width = 64, Data = Encoding.Default.GetBytes(new string('Z', 8192)), }; string resourcePatchData = Convert.ToBase64String(Encoding.Default.GetBytes(Skin.ToJson(resourcePatch))); string skin64 = Convert.ToBase64String(skin.Data); string skinData = $@" {{ ""AnimatedImageData"": [], ""CapeData"": """", ""CapeId"": """", ""CapeImageHeight"": 0, ""CapeImageWidth"": 0, ""CapeOnClassicSkin"": false, ""ClientRandomId"": {new Random().Next()}, ""CurrentInputMode"": 1, ""DefaultInputMode"": 1, ""DeviceId"": ""{Guid.NewGuid().ToString()}"", ""DeviceModel"": ""MiNET CLIENT"", ""DeviceOS"": 7, ""GameVersion"": ""{McpeProtocolInfo.GameVersion}"", ""GuiScale"": -1, ""LanguageCode"": ""en_US"", ""PersonaSkin"": false, ""PlatformOfflineId"": """", ""PlatformOnlineId"": """", ""PremiumSkin"": true, ""SelfSignedId"": ""{Guid.NewGuid().ToString()}"", ""ServerAddress"": ""yodamine.com:19132"", ""SkinAnimationData"": """", ""SkinData"": ""{skin64}"", ""SkinGeometryData"": """", ""SkinId"": ""{skin.SkinId}"", ""SkinImageHeight"": {skin.Height}, ""SkinImageWidth"": {skin.Width}, ""SkinResourcePatch"": ""{resourcePatchData}"", ""ThirdPartyName"": ""{username}"", ""ThirdPartyNameOnly"": false, ""UIProfile"": 0 }} "; ECDsa signKey = ConvertToSingKeyFormat(newKey); string b64Key = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newKey.Public).GetEncoded().EncodeBase64(); string val = JWT.Encode(skinData, signKey, JwsAlgorithm.ES384, new Dictionary <string, object> { { "x5u", b64Key } }); return(Encoding.UTF8.GetBytes(val)); }
private static SubjectPublicKeyInfo GetSubjectPublicKey(X509Certificate c) { return(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(c.GetPublicKey())); }
/// <summary> /// 从证书中提取公钥并转换为PEM编码 /// </summary> /// <param name="input">证书</param> /// <returns>PEM编码公钥</returns> public static string ExtractPemPublicKeyFromCert(X509Certificate input) { SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(input.GetPublicKey()); return(Convert.ToBase64String(subjectPublicKeyInfo.GetDerEncoded())); }
public SimpleTestResult EncodeDecodePublicLW(string oidStr, DerObjectIdentifier digest) { DerObjectIdentifier oid = ECGost3410NamedCurves.GetOid(oidStr); ECNamedDomainParameters ecp = new ECNamedDomainParameters(oid, ECGost3410NamedCurves.GetByOidX9(oid)); ECGost3410Parameters gostParams = new ECGost3410Parameters(ecp, oid, digest, null); ECKeyGenerationParameters parameters = new ECKeyGenerationParameters(gostParams, new SecureRandom()); ECKeyPairGenerator engine = new ECKeyPairGenerator(); engine.Init(parameters); AsymmetricCipherKeyPair pair = engine.GenerateKeyPair(); ECPublicKeyParameters generatedKeyParameters = (ECPublicKeyParameters)pair.Public; SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(generatedKeyParameters); ECPublicKeyParameters recoveredKeyParameters = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(info); { // Specifically cast and test gost parameters. ECGost3410Parameters gParam = (ECGost3410Parameters)generatedKeyParameters.Parameters; ECGost3410Parameters rParam = (ECGost3410Parameters)recoveredKeyParameters.Parameters; bool ok = SafeEquals(gParam.DigestParamSet, rParam.DigestParamSet) && SafeEquals(gParam.EncryptionParamSet, rParam.EncryptionParamSet) && SafeEquals(gParam.PublicKeyParamSet, rParam.PublicKeyParamSet); if (!ok) { return(new SimpleTestResult(false, "GOST parameters does not match")); } } if (!((ECGost3410Parameters)recoveredKeyParameters.Parameters).Name.Equals( ((ECGost3410Parameters)generatedKeyParameters.Parameters).Name)) { return(new SimpleTestResult(false, "Name does not match")); } if (recoveredKeyParameters.IsPrivate != generatedKeyParameters.IsPrivate) { return(new SimpleTestResult(false, "isPrivate does not match")); } if (!Arrays.AreEqual( recoveredKeyParameters.Q.GetEncoded(true), generatedKeyParameters.Q.GetEncoded(true))) { return(new SimpleTestResult(false, "Q does not match")); } if (!recoveredKeyParameters.Parameters.Curve.Equals(generatedKeyParameters.Parameters.Curve)) { return(new SimpleTestResult(false, "Curve does not match")); } if (!Arrays.AreEqual( recoveredKeyParameters.Parameters.G.GetEncoded(true), generatedKeyParameters.Parameters.G.GetEncoded(true))) { return(new SimpleTestResult(false, "G does not match")); } if (!recoveredKeyParameters.Parameters.H.Equals(generatedKeyParameters.Parameters.H)) { return(new SimpleTestResult(false, "H does not match")); } if (!recoveredKeyParameters.Parameters.HInv.Equals(generatedKeyParameters.Parameters.HInv)) { return(new SimpleTestResult(false, "Hinv does not match")); } if (!recoveredKeyParameters.Parameters.N.Equals(generatedKeyParameters.Parameters.N)) { return(new SimpleTestResult(false, "N does not match")); } if (!Arrays.AreEqual(recoveredKeyParameters.Parameters.GetSeed(), generatedKeyParameters.Parameters.GetSeed())) { return(new SimpleTestResult(false, "Seed does not match")); } return(new SimpleTestResult(true, null)); }
/// <summary> /// Creates a self signed application instance certificate. /// </summary> /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param> /// <param name="storePath">The store path (syntax depends on storeType).</param> /// <param name="password">The password to use to protect the certificate.</param> /// <param name="applicationUri">The application uri (created if not specified).</param> /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param> /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param> /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param> /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param> /// <param name="startTime">The start time.</param> /// <param name="lifetimeInMonths">The lifetime of the key in months.</param> /// <param name="hashSizeInBits">The hash size in bits.</param> /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param> /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param> /// <returns>The certificate with a private key.</returns> public static X509Certificate2 CreateCertificate( string storeType, string storePath, string password, string applicationUri, string applicationName, string subjectName, IList <String> domainNames, ushort keySize, DateTime startTime, ushort lifetimeInMonths, ushort hashSizeInBits, bool isCA = false, X509Certificate2 issuerCAKeyCert = null, byte[] publicKey = null) { if (issuerCAKeyCert != null) { if (!issuerCAKeyCert.HasPrivateKey) { throw new NotSupportedException("Cannot sign with a CA certificate without a private key."); } } if (publicKey != null && issuerCAKeyCert == null) { throw new NotSupportedException("Cannot use a public key without a CA certificate with a private key."); } // set default values. X509Name subjectDN = SetSuitableDefaults( ref applicationUri, ref applicationName, ref subjectName, ref domainNames, ref keySize, ref lifetimeInMonths); using (var cfrg = new CertificateFactoryRandomGenerator()) { // cert generators SecureRandom random = new SecureRandom(cfrg); X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); // Serial Number BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); cg.SetSerialNumber(serialNumber); // subject and issuer DN X509Name issuerDN = null; if (issuerCAKeyCert != null) { issuerDN = new CertificateFactoryX509Name(issuerCAKeyCert.Subject); } else { // self signed issuerDN = subjectDN; } cg.SetIssuerDN(issuerDN); cg.SetSubjectDN(subjectDN); // valid for cg.SetNotBefore(startTime); cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths)); // set Private/Public Key AsymmetricKeyParameter subjectPublicKey; AsymmetricKeyParameter subjectPrivateKey; if (publicKey == null) { var keyGenerationParameters = new KeyGenerationParameters(random, keySize); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair(); subjectPublicKey = subjectKeyPair.Public; subjectPrivateKey = subjectKeyPair.Private; } else { // special case, if a cert is signed by CA, the private key of the cert is not needed subjectPublicKey = PublicKeyFactory.CreateKey(publicKey); subjectPrivateKey = null; } cg.SetPublicKey(subjectPublicKey); // add extensions // Subject key identifier cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectPublicKey))); // Basic constraints cg.AddExtension(X509Extensions.BasicConstraints.Id, true, isCA ? new BasicConstraints(0) : new BasicConstraints(false)); // Authority Key identifier references the issuer cert or itself when self signed AsymmetricKeyParameter issuerPublicKey; BigInteger issuerSerialNumber; if (issuerCAKeyCert != null) { issuerPublicKey = GetPublicKeyParameter(issuerCAKeyCert); issuerSerialNumber = GetSerialNumber(issuerCAKeyCert); if (startTime.AddMonths(lifetimeInMonths) > issuerCAKeyCert.NotAfter) { cg.SetNotAfter(issuerCAKeyCert.NotAfter); } } else { issuerPublicKey = subjectPublicKey; issuerSerialNumber = serialNumber; } cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerPublicKey), new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber)); if (!isCA) { // Key usage var keyUsage = KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment; if (issuerCAKeyCert == null) { // only self signed certs need KeyCertSign flag. keyUsage |= KeyUsage.KeyCertSign; } cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage)); // Extended Key usage cg.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth })); // subject alternate name List <GeneralName> generalNames = new List <GeneralName>(); generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri)); generalNames.AddRange(CreateSubjectAlternateNameDomains(domainNames)); cg.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(generalNames.ToArray())); } else { // Key usage CA cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign)); } // sign certificate AsymmetricKeyParameter signingKey; if (issuerCAKeyCert != null) { // signed by issuer signingKey = GetPrivateKeyParameter(issuerCAKeyCert); } else { // self signed signingKey = subjectPrivateKey; } ISignatureFactory signatureFactory = new Asn1SignatureFactory(GetRSAHashAlgorithm(hashSizeInBits), signingKey, random); Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory); // convert to X509Certificate2 X509Certificate2 certificate = null; if (subjectPrivateKey == null) { // create the cert without the private key certificate = new X509Certificate2(x509.GetEncoded()); } else { // note: this cert has a private key! certificate = CreateCertificateWithPrivateKey(x509, null, subjectPrivateKey, random); } Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint); // add cert to the store. if (!String.IsNullOrEmpty(storePath) && !String.IsNullOrEmpty(storeType)) { using (ICertificateStore store = CertificateStoreIdentifier.CreateStore(storeType)) { if (store == null) { throw new ArgumentException("Invalid store type"); } store.Open(storePath); store.Add(certificate, password).Wait(); store.Close(); } } return(certificate); } }
private void doTestECDH( string algorithm) { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm); // EllipticCurve curve = new EllipticCurve( // new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q // new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a // new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, // ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n BigInteger.One); //1); // h // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // a side // AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // // aKeyAgreeBasic.doPhase(bKeyPair.Public, true); // bKeyAgreeBasic.doPhase(aKeyPair.Public, true); // // BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret()); // BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret()); BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(algorithm + " 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algorithm); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc); ECDomainParameters ecDP = pubKey.Parameters; // if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW())) ECPoint pq1 = pubKey.Q.Normalize(), pq2 = ((ECPublicKeyParameters)aKeyPair.Public).Q.Normalize(); if (!pq1.Equals(pq2)) { // Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX()); // Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY()); // Fail(algorithm + " public key encoding (W test) failed"); Console.WriteLine(" expected " + pq1.AffineXCoord.ToBigInteger() + " got " + pq2.AffineXCoord.ToBigInteger()); Console.WriteLine(" expected " + pq1.AffineYCoord.ToBigInteger() + " got " + pq2.AffineYCoord.ToBigInteger()); Fail(algorithm + " public key encoding (Q test) failed"); } // if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator())) if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G)) { Fail(algorithm + " public key encoding (G test) failed"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D)) { // Fail(algorithm + " private key encoding (S test) failed"); Fail(algorithm + " private key encoding (D test) failed"); } // if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator())) if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G)) { Fail(algorithm + " private key encoding (G test) failed"); } }
public SelfCertificateDialog(IServiceProvider serviceProvider) : base(serviceProvider) { InitializeComponent(); cbStore.SelectedIndex = 0; cbLength.SelectedIndex = 3; cbHashing.SelectedIndex = 1; txtCommonName.Text = Environment.MachineName; if (Environment.OSVersion.Version.Major < 8) { // IMPORTANT: WebHosting store is available since Windows 8. cbStore.Enabled = false; } if (!Helper.IsRunningOnMono()) { NativeMethods.TryAddShieldToButton(btnOK); } var container = new CompositeDisposable(); FormClosed += (sender, args) => container.Dispose(); container.Add( Observable.FromEventPattern <EventArgs>(txtName, "TextChanged") .Subscribe(evt => { btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text); })); container.Add( Observable.FromEventPattern <EventArgs>(btnOK, "Click") .Subscribe(evt => { // Generate certificate string defaultIssuer = string.Format("CN={0}", txtCommonName.Text); string defaultSubject = defaultIssuer; byte[] sn = Guid.NewGuid().ToByteArray(); string subject = defaultSubject; string issuer = defaultIssuer; DateTime notBefore = DateTime.Now; DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z RSA issuerKey = new RSACryptoServiceProvider(int.Parse(cbLength.Text)); RSA subjectKey = null; CspParameters subjectParams = new CspParameters(); CspParameters issuerParams = new CspParameters(); BasicConstraintsExtension bce = new BasicConstraintsExtension { PathLenConstraint = BasicConstraintsExtension.NoPathLengthConstraint, CertificateAuthority = true }; ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(); eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.1"); SubjectAltNameExtension alt = null; string p12File = Path.GetTempFileName(); string p12pwd = "test"; // serial number MUST be positive if ((sn[0] & 0x80) == 0x80) { sn[0] -= 0x80; } if (subject != defaultSubject) { issuer = subject; issuerKey = null; } else { subject = issuer; subjectKey = issuerKey; } if (subject == null) { throw new Exception("Missing Subject Name"); } X509CertificateBuilder cb = new X509CertificateBuilder(3); cb.SerialNumber = sn; cb.IssuerName = issuer; cb.NotBefore = notBefore; cb.NotAfter = notAfter; cb.SubjectName = subject; cb.SubjectPublicKey = subjectKey; // extensions if (bce != null) { cb.Extensions.Add(bce); } if (eku != null) { cb.Extensions.Add(eku); } if (alt != null) { cb.Extensions.Add(alt); } IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.GetRsaPublicKey(issuerKey)); byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); cb.Extensions.Add(new SubjectKeyIdentifierExtension { Identifier = resBuf }); cb.Extensions.Add(new AuthorityKeyIdentifierExtension { Identifier = resBuf }); // signature string hashName = cbHashing.SelectedIndex == 0 ? "SHA1" : "SHA256"; cb.Hash = hashName; byte[] rawcert = cb.Sign(issuerKey); PKCS12 p12 = new PKCS12(); p12.Password = p12pwd; ArrayList list = new ArrayList(); // we use a fixed array to avoid endianess issues // (in case some tools requires the ID to be 1). list.Add(new byte[] { 1, 0, 0, 0 }); Hashtable attributes = new Hashtable(1); attributes.Add(PKCS9.localKeyId, list); p12.AddCertificate(new X509Certificate(rawcert), attributes); p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes); p12.SaveToFile(p12File); Item = new X509Certificate2(p12File, p12pwd) { FriendlyName = txtName.Text }; Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting"; try { using (var process = new Process()) { // add certificate var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = string.Format("/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"", p12File, p12pwd, txtName.Text, cbStore.SelectedIndex == 0 ? "MY" : "WebHosting", Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")); start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); File.Delete(p12File); if (process.ExitCode == 0) { this.DialogResult = DialogResult.OK; } else { MessageBox.Show(process.ExitCode.ToString()); } } } catch (Exception) { // elevation is cancelled. } })); }
private void doTestGP( string algName, int size, int privateValueSize, BigInteger g, BigInteger p) { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator(algName); DHParameters dhParams = new DHParameters(p, g, null, privateValueSize); KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), dhParams); keyGen.Init(kgp); // // a side // AsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName); checkKeySize(privateValueSize, aKeyPair); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName); checkKeySize(privateValueSize, bKeyPair); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // // aKeyAgreeBasic.doPhase(bKeyPair.Public, true); // bKeyAgreeBasic.doPhase(aKeyPair.Public, true); // // BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret()); // BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret()); BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(size + " bit 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algName); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // DHPublicKey pubKey = (DHPublicKey)keyFac.generatePublic(pubX509); DHPublicKeyParameters pubKey = (DHPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc); // DHParameterSpec spec = pubKey.Parameters; DHParameters spec = pubKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit public key encoding/decoding test failed on parameters"); } if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key encoding/decoding test failed on y value"); } // // public key serialisation test // // TODO Put back in // MemoryStream bOut = new MemoryStream(); // ObjectOutputStream oOut = new ObjectOutputStream(bOut); // // oOut.WriteObject(aKeyPair.Public); // // MemoryStream bIn = new MemoryStream(bOut.ToArray(), false); // ObjectInputStream oIn = new ObjectInputStream(bIn); // // pubKey = (DHPublicKeyParameters)oIn.ReadObject(); spec = pubKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit public key serialisation test failed on parameters"); } if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key serialisation test failed on y value"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // DHPrivateKeyParameters privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8); DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc); spec = privKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit private key encoding/decoding test failed on parameters"); } if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key encoding/decoding test failed on y value"); } // // private key serialisation test // // TODO Put back in // bOut = new MemoryStream(); // oOut = new ObjectOutputStream(bOut); // // oOut.WriteObject(aKeyPair.Private); // // bIn = new MemoryStream(bOut.ToArray(), false); // oIn = new ObjectInputStream(bIn); // // privKey = (DHPrivateKeyParameters)oIn.ReadObject(); spec = privKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit private key serialisation test failed on parameters"); } if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key serialisation test failed on y value"); } // // three party test // IAsymmetricCipherKeyPairGenerator aPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); aPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair aPair = aPairGen.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator bPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); bPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair bPair = bPairGen.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator cPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); cPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair cPair = cPairGen.GenerateKeyPair(); IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement(algName); aKeyAgree.Init(aPair.Private); IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement(algName); bKeyAgree.Init(bPair.Private); IBasicAgreement cKeyAgree = AgreementUtilities.GetBasicAgreement(algName); cKeyAgree.Init(cPair.Private); // Key ac = aKeyAgree.doPhase(cPair.Public, false); // Key ba = bKeyAgree.doPhase(aPair.Public, false); // Key cb = cKeyAgree.doPhase(bPair.Public, false); // // aKeyAgree.doPhase(cb, true); // bKeyAgree.doPhase(ac, true); // cKeyAgree.doPhase(ba, true); // // BigInteger aShared = new BigInteger(aKeyAgree.generateSecret()); // BigInteger bShared = new BigInteger(bKeyAgree.generateSecret()); // BigInteger cShared = new BigInteger(cKeyAgree.generateSecret()); DHPublicKeyParameters ac = new DHPublicKeyParameters(aKeyAgree.CalculateAgreement(cPair.Public), spec); DHPublicKeyParameters ba = new DHPublicKeyParameters(bKeyAgree.CalculateAgreement(aPair.Public), spec); DHPublicKeyParameters cb = new DHPublicKeyParameters(cKeyAgree.CalculateAgreement(bPair.Public), spec); BigInteger aShared = aKeyAgree.CalculateAgreement(cb); BigInteger bShared = bKeyAgree.CalculateAgreement(ac); BigInteger cShared = cKeyAgree.CalculateAgreement(ba); if (!aShared.Equals(bShared)) { Fail(size + " bit 3-way test failed (a and b differ)"); } if (!cShared.Equals(bShared)) { Fail(size + " bit 3-way test failed (c and b differ)"); } }
/// <summary> /// Gets a security token from the federation server. /// </summary> /// <returns> /// The security token, which is basically a JWT token string. /// </returns> private SecurityTokenAdapter GetSecurityTokenFromServer() { logger.Info("Getting security token from the auth server"); var keyPair = sessionKeySupplier.GetKeyPair(); if (keyPair == null) { throw new InvalidOperationException("Keypair is not generated, it is null"); } var publicKey = (RsaKeyParameters)keyPair.Public; if (publicKey == null) { throw new InvalidOperationException("Public key is missing in the key pair"); } string publicKeyDerBase64 = null; try { byte[] publicKeyDer = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey).GetDerEncoded(); publicKeyDerBase64 = Convert.ToBase64String(publicKeyDer); } catch (Exception e) { throw new InvalidOperationException("Failed to convert public key from RsaKeyParameters type to string type", e); } var certificateAndKeyPair = leafCertificateSupplier.GetCertificateAndKeyPair(); if (certificateAndKeyPair == null) { throw new InvalidOperationException("Certificate and key pair are not present"); } var leafCertificate = certificateAndKeyPair.Certificate; if (leafCertificate == null) { throw new InvalidOperationException("Leaf certificate is not present"); } if (certificateAndKeyPair.PrivateKey == null) { throw new InvalidOperationException("Leaf certificate's private key is missing"); } HashSet <string> intermediateStrings = null; if (intermediateCertificateSuppliers != null && intermediateCertificateSuppliers.Count > 0) { logger.Debug("Intermediate certificate(s) were supplied"); intermediateStrings = new HashSet <string>(); foreach (var supplier in intermediateCertificateSuppliers) { var supplierCertificateAndKeyPair = supplier.GetCertificateAndKeyPair(); if (supplierCertificateAndKeyPair != null && supplierCertificateAndKeyPair.Certificate != null) { intermediateStrings.Add(Convert.ToBase64String(supplierCertificateAndKeyPair.Certificate.RawData)); } } } // create request body to be sent to the auth service var url = this.federationEndpoint + Constants.AUTH_SERVICE_PATH; var requestBody = new X509FederationRequest(publicKeyDerBase64, Convert.ToBase64String(leafCertificate.RawData), intermediateStrings, purpose); var httpRequestMsg = new HttpRequestMessage(HttpMethod.Post, new Uri(url)); httpRequestMsg.Content = ContentHelper.CreateHttpContent(requestBody); var keyId = this.tenancyId + Constants.FED_KEY_PATH + AuthUtils.GetFingerPrint(leafCertificate.Thumbprint); if (FederationSigner == null) { FederationSigner = new FederationRequestSigner((RsaKeyParameters)certificateAndKeyPair.PrivateKey, keyId); } FederationSigner.SignRequest(httpRequestMsg); var requestContent = httpRequestMsg.Content.ReadAsStringAsync().Result; logger.Debug($"request content to Auth service is {requestContent}"); HttpResponseMessage response = null; try { if (Client == null) { Client = new HttpClient(); } for (int retry = 0; retry < Constants.RETRIES; retry++) { // A new copy of the request message needs to be created because it is disposed each time it is sent, and // resending the same request will result in the following error message: // "The request message was already sent. Cannot send the same request message multiple times." var newRequestMessage = HttpUtils.CloneHttpRequestMessage(httpRequestMsg); response = Client.SendAsync(newRequestMessage).Result; if (response.IsSuccessStatusCode) { break; } Thread.Sleep(Constants.RETRY_MILLIS); } if (response == null || !response.IsSuccessStatusCode) { logger.Debug("Received non successful response while trying to get the AUTH token"); ResponseHelper.HandleNonSuccessfulResponse(response); } } finally { Client.Dispose(); Client = null; } var securityTokenContent = response.Content.ReadAsStringAsync().Result; var securityToken = JsonConvert.DeserializeObject <SecurityToken>(securityTokenContent); logger.Info($"Security Token received from the Auth Service"); return(new SecurityTokenAdapter(securityToken.Token)); }
public override void PerformTest() { X509CertificateParser certParser = new X509CertificateParser(); X509CrlParser crlParser = new X509CrlParser(); X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); X509Crl rootCrl = crlParser.ReadCrl(CertPathTest.rootCrlBin); X509Crl interCrl = crlParser.ReadCrl(CertPathTest.interCrlBin); // Testing CollectionCertStore generation from List IList certList = new ArrayList(); certList.Add(rootCert); certList.Add(interCert); certList.Add(finalCert); IX509Store certStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // set default to be the same as for SUN X500 name X509Name.DefaultReverse = true; // Searching for rootCert by subjectDN X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); IList certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by subjectDN"); } // Searching for rootCert by subjectDN encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded subjectDN"); } X509Name.DefaultReverse = false; // Searching for rootCert by public key encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.SubjectPublicKey = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCert.GetPublicKey()); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded public key"); } // Searching for interCert by issuerDN targetConstraints = new X509CertStoreSelector(); targetConstraints.Issuer = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 2) { Fail("did not found 2 certs"); } if (!certs.Contains(rootCert)) { Fail("rootCert not found"); } if (!certs.Contains(interCert)) { Fail("interCert not found"); } // Searching for rootCrl by issuerDN IList crlList = new ArrayList(); crlList.Add(rootCrl); crlList.Add(interCrl); IX509Store store = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(crlList)); X509CrlStoreSelector targetConstraintsCRL = new X509CrlStoreSelector(); ArrayList issuers = new ArrayList(); issuers.Add(rootCrl.IssuerDN); targetConstraintsCRL.Issuers = issuers; IList crls = new ArrayList(store.GetMatches(targetConstraintsCRL)); if (crls.Count != 1 || !crls.Contains(rootCrl)) { Fail("rootCrl not found"); } crls = new ArrayList(certStore.GetMatches(targetConstraintsCRL)); if (crls.Count != 0) { Fail("error using wrong selector (CRL)"); } certs = new ArrayList(store.GetMatches(targetConstraints)); if (certs.Count != 0) { Fail("error using wrong selector (certs)"); } // Searching for attribute certificates X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert); IX509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID); IList attrList = new ArrayList(); attrList.Add(attrCert); attrList.Add(attrCert2); store = X509StoreFactory.Create( "AttributeCertificate/Collection", new X509CollectionStoreParameters(attrList)); X509AttrCertStoreSelector attrSelector = new X509AttrCertStoreSelector(); attrSelector.Holder = attrCert.Holder; if (!attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } IList attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on holder"); } attrSelector.Holder = attrCert2.Holder; if (attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on holder"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.Issuer = attrCert.Issuer; if (!attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on issuer"); } attrSelector.Issuer = attrCert2.Issuer; if (attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on issuer"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCert = attrCert; if (!attrSelector.AttributeCert.Equals(attrCert)) { Fail("attrCert get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on attrCert"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.SerialNumber = attrCert.SerialNumber; if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = (X509AttrCertStoreSelector)attrSelector.Clone(); if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore); if (attrSelector.AttributeCertificateValid.Value != attrCert.NotBefore) { Fail("valid get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on valid"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore.AddMilliseconds(-100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on before"); } attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotAfter.AddMilliseconds(100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on after"); } attrSelector.SerialNumber = BigInteger.ValueOf(10000); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on wrong serial number"); } attrSelector.AttributeCert = null; attrSelector.AttributeCertificateValid = null; attrSelector.Holder = null; attrSelector.Issuer = null; attrSelector.SerialNumber = null; if (attrSelector.AttributeCert != null) { Fail("null attrCert"); } if (attrSelector.AttributeCertificateValid != null) { Fail("null attrCertValid"); } if (attrSelector.Holder != null) { Fail("null attrCert holder"); } if (attrSelector.Issuer != null) { Fail("null attrCert issuer"); } if (attrSelector.SerialNumber != null) { Fail("null attrCert serial"); } attrs = new ArrayList(certStore.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("error using wrong selector (attrs)"); } certPairTest(); }
static void Main(string[] args) { var assembly = Assembly.GetExecutingAssembly(); var title = (AssemblyTitleAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute)); Console.WriteLine("{0} version {1}", title.Title, assembly.GetName().Version); var copyright = (AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute)); Console.WriteLine(copyright.Copyright); Console.WriteLine("More information can be found at https://www.jexusmanager.com"); Console.WriteLine(); var baseAddress = args.Length > 0 ? args[0] : "https://*****:*****@"Remote services must be run as root on Linux."); return; } if (!File.Exists("jws")) { Console.WriteLine(@"Remote services must be running in Jexus installation folder."); return; } var loc = baseAddress.LastIndexOf(':'); var port = "443"; if (loc != -1) { port = baseAddress.Substring(loc + 1); } string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string path = Path.Combine(dirname, ".mono", "httplistener"); if (false == Directory.Exists(path)) { Directory.CreateDirectory(path); } string target_cert = Path.Combine(path, string.Format("{0}.cer", port)); if (File.Exists(target_cert)) { Console.WriteLine("Use {0}", target_cert); } else { Console.WriteLine("Generating a self-signed certificate for Jexus Manager"); // Generate certificate string defaultIssuer = "CN=jexus.lextudio.com"; string defaultSubject = "CN=jexus.lextudio.com"; byte[] sn = Guid.NewGuid().ToByteArray(); string subject = defaultSubject; string issuer = defaultIssuer; DateTime notBefore = DateTime.Now; DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z RSA issuerKey = new RSACryptoServiceProvider(2048); RSA subjectKey = null; bool selfSigned = true; string hashName = "SHA1"; CspParameters subjectParams = new CspParameters(); CspParameters issuerParams = new CspParameters(); BasicConstraintsExtension bce = new BasicConstraintsExtension { PathLenConstraint = BasicConstraintsExtension.NoPathLengthConstraint, CertificateAuthority = true }; ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(); eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.1"); SubjectAltNameExtension alt = null; string p12file = Path.Combine(path, "temp.pfx"); string p12pwd = "test"; // serial number MUST be positive if ((sn[0] & 0x80) == 0x80) { sn[0] -= 0x80; } if (selfSigned) { if (subject != defaultSubject) { issuer = subject; issuerKey = subjectKey; } else { subject = issuer; subjectKey = issuerKey; } } if (subject == null) { throw new Exception("Missing Subject Name"); } X509CertificateBuilder cb = new X509CertificateBuilder(3); cb.SerialNumber = sn; cb.IssuerName = issuer; cb.NotBefore = notBefore; cb.NotAfter = notAfter; cb.SubjectName = subject; cb.SubjectPublicKey = subjectKey; // extensions if (bce != null) { cb.Extensions.Add(bce); } if (eku != null) { cb.Extensions.Add(eku); } if (alt != null) { cb.Extensions.Add(alt); } IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.GetRsaPublicKey(issuerKey)); byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); cb.Extensions.Add(new SubjectKeyIdentifierExtension { Identifier = resBuf }); cb.Extensions.Add(new AuthorityKeyIdentifierExtension { Identifier = resBuf }); // signature cb.Hash = hashName; byte[] rawcert = cb.Sign(issuerKey); PKCS12 p12 = new PKCS12(); p12.Password = p12pwd; ArrayList list = new ArrayList(); // we use a fixed array to avoid endianess issues // (in case some tools requires the ID to be 1). list.Add(new byte[4] { 1, 0, 0, 0 }); Hashtable attributes = new Hashtable(1); attributes.Add(PKCS9.localKeyId, list); p12.AddCertificate(new Mono.Security.X509.X509Certificate(rawcert), attributes); p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes); p12.SaveToFile(p12file); var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(p12file, p12pwd, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); // Install certificate string target_pvk = Path.Combine(path, string.Format("{0}.pvk", port)); using (Stream cer = File.OpenWrite(target_cert)) { byte[] raw = x509.RawData; cer.Write(raw, 0, raw.Length); } PrivateKey pvk = new PrivateKey(); pvk.RSA = subjectKey; pvk.Save(target_pvk); } } JexusServer.Credentials = args.Length > 2 ? args[1] + "|" + args[2] : "jexus|lextudio.com"; JexusServer.Timeout = args.Length > 3 ? double.Parse(args[3]) : 30D; using (WebApp.Start <Startup>(url: baseAddress)) { Console.WriteLine("Remote services have started at {0}.", baseAddress); Console.WriteLine("Credentials is {0}", JexusServer.Credentials); Console.WriteLine("Press Enter to quit."); Console.ReadLine(); } }