public ScrambledKeyPair(AsymmetricCipherKeyPair pPair)
 {
     _pair = pPair;
     _publicKey = pPair.getPublic();
     _scrambledModulus = scrambleModulus((_publicKey as RSAKeyParameters).getModulus());
     _privateKey = pPair.getPrivate();
 }
Beispiel #2
0
        public SimpleTestResult EncodeDecodePublicLW(string oidStr, DerObjectIdentifier digest)
        {
            DerObjectIdentifier       oid        = ECGost3410NamedCurves.GetOid(oidStr);
            ECNamedDomainParameters   ecp        = new ECNamedDomainParameters(oid, ECGost3410NamedCurves.GetByOid(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));
        }
        public static X509Certificate2 IssueCert(string pathToPfxFile, string password, string commonName, out AsymmetricCipherKeyPair certificateSubjectKeyPair)
        {
            var issuerCertificate = new X509Certificate2(pathToPfxFile, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            if (!issuerCertificate.HasPrivateKey)
            {
                throw new InvalidOperationException("The authority's .pfx file does not have a private key.");
            }

            var keyUsages         = KeyUsage.DataEncipherment | KeyUsage.KeyEncipherment | KeyUsage.DigitalSignature;
            var extendedKeyUsages = new List <KeyPurposeID>(new[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth });

            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            certificateSubjectKeyPair = GenerateRsaKeyPair(random, 2048);
            var subjectSerialNumber    = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            var subjectDn              = $"C=US,ST=NY,L=New York,STREET=123 Main St,[email protected],O=Sample Certs,OU=MegaCorp,CN={commonName}";
            var bcIssuerCertificate    = DotNetUtilities.FromX509Certificate(issuerCertificate);
            var issuerDn               = bcIssuerCertificate.SubjectDN.ToString();
            var issuerKeyPair          = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
            var signatureAlgorithmName = bcIssuerCertificate.SigAlgOid;

            var certificate = GenerateCertificate(random, subjectDn, certificateSubjectKeyPair, subjectSerialNumber,
                                                  GetAllSan(), issuerDn, issuerKeyPair, keyUsages, extendedKeyUsages, 30, signatureAlgorithmName);

            var convertedCertificate = ConvertCertificate(certificate, certificateSubjectKeyPair, random);

            convertedCertificate.FriendlyName = commonName;
            return(convertedCertificate);
        }
        private static X509Certificate2 ConvertCertificate(Org.BouncyCastle.X509.X509Certificate certificate, AsymmetricCipherKeyPair subjectKeyPair, SecureRandom random)
        {
            // Now to convert the Bouncy Castle certificate to a .NET certificate. Basically, we create a PKCS12 store (a .PFX file) in memory,
            // and add the public and private key to that.
            var store = new Pkcs12Store();

            // What Bouncy Castle calls "alias" is the same as what Windows terms the "friendly name".
            string friendlyName = certificate.SubjectDN.ToString();

            // Add the certificate.
            var certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);

            // Add the private key.
            var keyEntry = new AsymmetricKeyEntry(subjectKeyPair.Private);

            store.SetKeyEntry(friendlyName, keyEntry, new[] { certificateEntry });

            // Convert it to an X509Certificate2 object by saving/loading it from a MemoryStream.
            // It needs a password. Since we'll remove this when the certificate is loaded as a X509Certificate2,
            // it doesn't particularly matter what we use.
            var stream         = new MemoryStream();
            var passwordString = "temp";
            var passwordChars  = passwordString.ToCharArray();

            store.Save(stream, passwordChars, random);

            var convertedCertificate = new X509Certificate2(stream.ToArray(), passwordString, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

            return(convertedCertificate);
        }
Beispiel #5
0
 public CryptoProvider(AsymmetricCipherKeyPair keyPair)
 {
     KeyPair = keyPair;
 }
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            AsymmetricKeyParameter senderPublicKey     = senderKeyPair.Public;
            ICipherParameters      senderPrivateParams = senderKeyPair.Private;


            OriginatorIdentifierOrKey originator;

            try
            {
                originator = new OriginatorIdentifierOrKey(
                    CreateOriginatorPublicKey(senderPublicKey));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }


            Asn1OctetString ukm = null;

            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator ephemKPG =
                        GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    ephemKPG.Init(
                        ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));

                    AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();

                    ukm = new DerOctetString(
                        new MQVuserKeyingMaterial(
                            CreateOriginatorPublicKey(ephemKP.Public), null));

                    senderPrivateParams = new MqvPrivateParameters(
                        (ECPrivateKeyParameters)senderPrivateParams,
                        (ECPrivateKeyParameters)ephemKP.Private,
                        (ECPublicKeyParameters)ephemKP.Public);
                }
                catch (IOException e)
                {
                    throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
                }
                catch (SecurityUtilityException e)
                {
                    throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
                }
            }


            DerSequence paramSeq = new DerSequence(
                keyEncryptionOID,
                DerNull.Instance);
            AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);


            Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();

            foreach (X509Certificate recipientCert in recipientCerts)
            {
                TbsCertificateStructure tbsCert;
                try
                {
                    tbsCert = TbsCertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
                }
                catch (Exception)
                {
                    throw new ArgumentException("can't extract TBS structure from certificate");
                }

                // TODO Should there be a SubjectKeyIdentifier-based alternative?
                IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
                    tbsCert.Issuer, tbsCert.SerialNumber.Value);
                KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);

                ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
                if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                {
                    recipientPublicParams = new MqvPublicParameters(
                        (ECPublicKeyParameters)recipientPublicParams,
                        (ECPublicKeyParameters)recipientPublicParams);
                }

                // Use key agreement to choose a wrap key for this recipient
                IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    keyAgreementOID, keyEncryptionOID.Id);
                keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
                BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);

                int          keyEncryptionKeySize  = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                byte[]       keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
                KeyParameter keyEncryptionKey      = ParameterUtilities.CreateKeyParameter(
                    keyEncryptionOID, keyEncryptionKeyBytes);

                // Wrap the content encryption key with the agreement key
                IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
                keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
                byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

                Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);

                recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
            }

            return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
                                                               new DerSequence(recipientEncryptedKeys))));
        }
Beispiel #7
0
        private void v0Test()
        {
            // create certificates and CRLs
            AsymmetricCipherKeyPair rootPair  = TestUtilities.GenerateRsaKeyPair();
            AsymmetricCipherKeyPair interPair = TestUtilities.GenerateRsaKeyPair();
            AsymmetricCipherKeyPair endPair   = TestUtilities.GenerateRsaKeyPair();

            X509Certificate rootCert  = TestUtilities.GenerateRootCert(rootPair);
            X509Certificate interCert = TestUtilities.GenerateIntermediateCert(interPair.Public, rootPair.Private, rootCert);
            X509Certificate endCert   = TestUtilities.GenerateEndEntityCert(endPair.Public, interPair.Private, interCert);

            BigInteger revokedSerialNumber = BigInteger.Two;
            X509Crl    rootCRL             = TestUtilities.CreateCrl(rootCert, rootPair.Private, revokedSerialNumber);
            X509Crl    interCRL            = TestUtilities.CreateCrl(interCert, interPair.Private, revokedSerialNumber);

            // create CertStore to support path building
            IList certList = new ArrayList();

            certList.Add(rootCert);
            certList.Add(interCert);
            certList.Add(endCert);

            IList crlList = new ArrayList();

            crlList.Add(rootCRL);
            crlList.Add(interCRL);

//			CollectionCertStoreParameters parameters = new CollectionCertStoreParameters(list);
//			CertStore                     store = CertStore.getInstance("Collection", parameters);
            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));
            IX509Store x509CrlStore = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            ISet trust = new HashSet();

            trust.Add(new TrustAnchor(rootCert, null));

            // build the path
//			CertPathBuilder  builder = CertPathBuilder.getInstance("PKIX", "BC");
            PkixCertPathBuilder   builder         = new PkixCertPathBuilder();
            X509CertStoreSelector pathConstraints = new X509CertStoreSelector();

            pathConstraints.Subject = endCert.SubjectDN;

            PkixBuilderParameters buildParams = new PkixBuilderParameters(trust, pathConstraints);

//			buildParams.addCertStore(store);
            buildParams.AddStore(x509CertStore);
            buildParams.AddStore(x509CrlStore);

            buildParams.Date = new DateTimeObject(DateTime.UtcNow);

            PkixCertPathBuilderResult result = builder.Build(buildParams);
            PkixCertPath path = result.CertPath;

            if (path.Certificates.Count != 2)
            {
                Fail("wrong number of certs in v0Test path");
            }
        }
Beispiel #8
0
        /// <summary>
        /// Creates a cert with the connectionstring (token) and stores it in the given cert store.
        /// </summary>
        public async static Task WriteAsync(string name, string connectionString, string storeType, string storePath)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();

            ArrayList nameOids = new ArrayList();
            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();
            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);
            cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment));

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA rsa = RSA.Create();
            RSAParameters rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!");
                }
            }

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;
            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                Pkcs12Store pkcsStore = builder.Build();
                X509CertificateEntry[] chain = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // handle each store type differently
                switch (storeType)
                {
                    case CertificateStoreType.Directory:
                        {
                            // Add to DirectoryStore
                            using (DirectoryCertificateStore store = new DirectoryCertificateStore())
                            {
                                store.Open(storePath);
                                X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        await store.Delete(cert.Thumbprint).ConfigureAwait(false);
                                    }
                                }

                                // add new one
                                await store.Add(certificate).ConfigureAwait(false);
                            }
                            break;
                        }
                    case CertificateStoreType.X509Store:
                        {
                            // Add to X509Store
                            using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser))
                            {
                                store.Open(OpenFlags.ReadWrite);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in store.Certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        store.Remove(cert);
                                    }
                                }

                                // add new cert to store
                                try
                                {
                                    store.Add(certificate);
                                }
                                catch (Exception e)
                                {
                                    throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'.");
                                }
                            }
                            break;
                        }
                    default:
                        {
                            throw new Exception($"The requested store type '{storeType}' is not supported. Please change.");
                        }
                }
                return;
            }
        }
Beispiel #9
0
        public override X509Certificate2 LoadApplicationCertificate(string thumbprint, string subjectName, string applicationURI, string password)
        {
            try
            {
                // Create a handle based on the hash of the keys
                ushort    slotIndex = ushort.Parse(thumbprint);
                TpmHandle nvHandle  = TpmHandle.NV(slotIndex);
                ushort    offset    = 0;

                // Read the serial number
                byte[] serialNumber = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(long), offset);
                offset += sizeof(long);

                // Read the "valid from" date (today) in FileTime format
                byte[] validFrom = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(long), offset);
                offset += sizeof(long);

                // Read size of keys from NV storage (located in the first 4 bytes)
                byte[] certSizeBlob = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(int), offset);
                offset += sizeof(int);

                // Read keys from NV storage in 64-byte chunks
                int    certSize   = BitConverter.ToInt32(certSizeBlob, 0);
                byte[] rawData    = new byte[certSize];
                ushort index      = 0;
                ushort sizeToRead = 0;
                while (index < certSize)
                {
                    if ((certSize - index) < 64)
                    {
                        sizeToRead = (ushort)(certSize - index);
                    }
                    else
                    {
                        sizeToRead = 64;
                    }

                    byte[] dataToRead = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeToRead, offset);
                    offset += sizeToRead;

                    for (int i = 0; i < sizeToRead; i++)
                    {
                        rawData[index + i] = dataToRead[i];
                    }

                    index += sizeToRead;
                }

                // Import
                TextReader textReader        = new StringReader(new string(Encoding.ASCII.GetChars(rawData)));
                PemReader  pemReader         = new PemReader(textReader);
                AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pemReader.ReadObject();

                X509Name   CN            = new X509Name("CN=" + subjectName + ",DC=" + Utils.GetHostName());
                BigInteger SN            = new BigInteger(serialNumber).Abs();
                DateTime   validFromDate = DateTime.FromFileTime(BitConverter.ToInt64(validFrom, 0));

                // Certificate Generator
                X509V3CertificateGenerator cGenerator = new X509V3CertificateGenerator();
                cGenerator.SetSerialNumber(SN);
                cGenerator.SetSubjectDN(CN);
                cGenerator.SetIssuerDN(CN);
                cGenerator.SetNotBefore(validFromDate);
                cGenerator.SetNotAfter(validFromDate.AddYears(1));
                cGenerator.SetPublicKey(keys.Public);
                cGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
                }));
                cGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public), new GeneralNames(new GeneralName(CN)), SN));
                cGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, applicationURI)));

                ISignatureFactory signatureFactory         = new Asn1SignatureFactory("SHA1withRSA", keys.Private, new SecureRandom());
                Org.BouncyCastle.X509.X509Certificate cert = cGenerator.Generate(signatureFactory);
                X509Certificate2 certificate = new X509Certificate2(cert.GetEncoded());

                RSACng rsa = new RSACng();
                RsaPrivateCrtKeyParameters keyParams = (RsaPrivateCrtKeyParameters)keys.Private;

                m_RSAParams = new RSAParameters();

                m_RSAParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
                keyParams.Modulus.ToByteArrayUnsigned().CopyTo(m_RSAParams.Modulus, 0);

                m_RSAParams.P = new byte[keyParams.P.ToByteArrayUnsigned().Length];
                keyParams.P.ToByteArrayUnsigned().CopyTo(m_RSAParams.P, 0);

                m_RSAParams.Q = new byte[keyParams.Q.ToByteArrayUnsigned().Length];
                keyParams.Q.ToByteArrayUnsigned().CopyTo(m_RSAParams.Q, 0);

                m_RSAParams.DP = new byte[keyParams.DP.ToByteArrayUnsigned().Length];
                keyParams.DP.ToByteArrayUnsigned().CopyTo(m_RSAParams.DP, 0);

                m_RSAParams.DQ = new byte[keyParams.DQ.ToByteArrayUnsigned().Length];
                keyParams.DQ.ToByteArrayUnsigned().CopyTo(m_RSAParams.DQ, 0);

                m_RSAParams.InverseQ = new byte[keyParams.QInv.ToByteArrayUnsigned().Length];
                keyParams.QInv.ToByteArrayUnsigned().CopyTo(m_RSAParams.InverseQ, 0);

                m_RSAParams.D = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
                keyParams.Exponent.ToByteArrayUnsigned().CopyTo(m_RSAParams.D, 0);

                m_RSAParams.Exponent = new byte[keyParams.PublicExponent.ToByteArrayUnsigned().Length];
                keyParams.PublicExponent.ToByteArrayUnsigned().CopyTo(m_RSAParams.Exponent, 0);

                rsa.ImportParameters(m_RSAParams);
                if (rsa != null)
                {
                    int    inputBlockSize = rsa.KeySize / 8 - 42;
                    byte[] bytes1         = rsa.Encrypt(new byte[inputBlockSize], RSAEncryptionPadding.OaepSHA1);
                    byte[] bytes2         = rsa.Decrypt(bytes1, RSAEncryptionPadding.OaepSHA1);
                    if (bytes2 != null)
                    {
                        return(certificate);
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Could not load application certificate " + subjectName);
            }

            return(null);
        }
Beispiel #10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            const string Algorithm               = "ECDH"; //What do you think about the other algorithms?
            const int    KeyBitSize              = 2056;
            const int    NonceBitSize            = 128;
            const int    MacBitSize              = 128;
            const int    DefaultPrimeProbability = 30;

            //BEGIN SETUP ALICE
            IAsymmetricCipherKeyPairGenerator aliceKeyGen    = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            DHParametersGenerator             aliceGenerator = new DHParametersGenerator();

            aliceGenerator.Init(KeyBitSize, DefaultPrimeProbability, new SecureRandom());
            DHParameters aliceParameters = aliceGenerator.GenerateParameters();

            KeyGenerationParameters aliceKGP = new DHKeyGenerationParameters(new SecureRandom(), aliceParameters);

            aliceKeyGen.Init(aliceKGP);

            AsymmetricCipherKeyPair aliceKeyPair  = aliceKeyGen.GenerateKeyPair();
            IBasicAgreement         aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            aliceKeyAgree.Init(aliceKeyPair.Private);

            Button   a1b             = FindViewById <Button>(Resource.Id.a1b);
            TextView AliceRandomText = FindViewById <TextView>(Resource.Id.a1t);

            Button   a2b = FindViewById <Button>(Resource.Id.a2b);
            TextView AlicePrivateKeyText = FindViewById <TextView>(Resource.Id.a2t);

            Button   a3b = FindViewById <Button>(Resource.Id.a3b);
            TextView AlicePublicKeyText = FindViewById <TextView>(Resource.Id.a3t);

            Button   b1b           = FindViewById <Button>(Resource.Id.b1b);
            TextView BobRandomText = FindViewById <TextView>(Resource.Id.b1t);

            Button   b2b = FindViewById <Button>(Resource.Id.b2b);
            TextView BobPrivateKeyText = FindViewById <TextView>(Resource.Id.b2t);

            Button   b3b = FindViewById <Button>(Resource.Id.b3b);
            TextView BobPublicKeyText = FindViewById <TextView>(Resource.Id.b3t);

            Button   a4b = FindViewById <Button>(Resource.Id.a4b);
            TextView AliceBobSharedKeyText = FindViewById <TextView>(Resource.Id.a4t);

            Button   b4b = FindViewById <Button>(Resource.Id.b4b);
            TextView BobAliceSharedKeyText = FindViewById <TextView>(Resource.Id.b4t);


            // what Alice does
            byte[] aliceRandomBytes = new byte[32];
            RNGCryptoServiceProvider.Create().GetBytes(aliceRandomBytes);

            byte[] alicePrivate = Curve25519.(aliceRandomBytes);
            byte[] alicePublic  = Curve25519.GetPublicKey(alicePrivate);

            // what Bob does
            byte[] bobRandomBytes = new byte[32];
            RNGCryptoServiceProvider.Create().GetBytes(bobRandomBytes);

            byte[] bobPrivate = Curve25519.ClampPrivateKey(bobRandomBytes);
            byte[] bobPublic  = Curve25519.GetPublicKey(bobPrivate);

            // what Alice does with Bob's public key
            byte[] aliceShared = Curve25519.GetSharedSecret(alicePrivate, bobPublic);

            // what Bob does with Alice' public key
            byte[] bobShared = Curve25519.GetSharedSecret(bobPrivate, alicePublic);

            // aliceShared == bobShared

            a1b.Click += delegate {
                alicePrivateBytes        = null;
                AlicePrivateKeyText.Text = "";

                alicePublicBytes        = null;
                AlicePublicKeyText.Text = "";

                aliceBobSharedBytes = null;
                bobAliceSharedBytes = null;

                AliceBobSharedKeyText.Text = "";
                BobAliceSharedKeyText.Text = "";

                aliceRandomBytes = new byte[32];
                RNGCryptoServiceProvider.Create().GetBytes(aliceRandomBytes);
                AliceRandomText.Text = BitConverter.ToString(aliceRandomBytes).Replace("-", "");
            };

            a2b.Click += delegate {
                if (aliceRandomBytes != null)
                {
                    alicePrivateBytes        = Curve25519.Create(aliceRandomBytes);
                    AlicePrivateKeyText.Text = BitConverter.ToString(alicePrivateBytes).Replace("-", "");
                }
            };

            a3b.Click += delegate {
                if (alicePrivateBytes != null)
                {
                    alicePublicBytes        = Curve25519.GetPublicKey(alicePrivateBytes);
                    AlicePublicKeyText.Text = BitConverter.ToString(alicePublicBytes).Replace("-", "");
                }
            };

            b1b.Click += delegate {
                bobPrivateBytes        = null;
                BobPrivateKeyText.Text = ""; // Reset

                bobPublicBytes        = null;
                BobPublicKeyText.Text = ""; // Reset

                aliceBobSharedBytes = null;
                bobAliceSharedBytes = null;

                AliceBobSharedKeyText.Text = "";
                BobAliceSharedKeyText.Text = "";

                bobRandomBytes = new byte[32];
                RNGCryptoServiceProvider.Create().GetBytes(bobRandomBytes);
                BobRandomText.Text = BitConverter.ToString(bobRandomBytes).Replace("-", "");
            };


            b2b.Click += delegate {
                if (bobRandomBytes != null)
                {
                    bobPrivateBytes        = Curve25519.ClampPrivateKey(bobRandomBytes);
                    BobPrivateKeyText.Text = BitConverter.ToString(bobPrivateBytes).Replace("-", "");
                }
            };

            b3b.Click += delegate {
                if (bobPrivateBytes != null)
                {
                    bobPublicBytes        = Curve25519.GetPublicKey(bobPrivateBytes);
                    BobPublicKeyText.Text = BitConverter.ToString(bobPublicBytes).Replace("-", "");
                }
            };

            a4b.Click += delegate {
                if ((alicePrivateBytes != null) && (bobPublicBytes != null))
                {
                    aliceBobSharedBytes        = Curve25519.GetSharedSecret(alicePrivateBytes, bobPublicBytes);
                    AliceBobSharedKeyText.Text = BitConverter.ToString(aliceBobSharedBytes).Replace("-", "");
                }
            };


            b4b.Click += delegate {
                if ((bobPrivateBytes != null) && (alicePublicBytes != null))
                {
                    bobAliceSharedBytes        = Curve25519.GetSharedSecret(bobPrivateBytes, alicePublicBytes);
                    BobAliceSharedKeyText.Text = BitConverter.ToString(bobAliceSharedBytes).Replace("-", "");
                }
            };
        }
Beispiel #11
0
        public override void PerformTest()
        {
            PgpPublicKey pubKey = null;

            //
            // Read the public key
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
            PgpPublicKeyRing pgpPub  = (PgpPublicKeyRing)pgpFact.NextPgpObject();

            pubKey = pgpPub.GetPublicKey();

            if (pubKey.BitStrength != 1024)
            {
                Fail("failed - key strength reported incorrectly.");
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey       = new PgpSecretKeyRing(testPrivKeyRing);
            PgpSecretKey     secretKey  = sKey.GetSecretKey();
            PgpPrivateKey    pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // signature generation
            //
            const string data = "hello world!";

            byte[]                dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream          bOut      = new MemoryStream();
            MemoryStream          testIn    = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen      = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa,
                                                                        HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(
                cGen.Open(new UncloseableStream(bOut)));

            sGen.GenerateOnePassVersion(false).Encode(bcOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            DateTime testDateTime = new DateTime(1973, 7, 27);
            Stream   lOut         = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            int ch;

            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            //
            // verify Generated signature
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            PgpOnePassSignature ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed Generated signature check");
            }

            //
            // test encryption
            //

            //
            // find a key sutiable for encryption
            //
            long pgpKeyID = 0;
            AsymmetricKeyParameter pKey = null;

            foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
            {
                if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt ||
                    pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral)
                {
                    pKey     = pgpKey.GetKey();
                    pgpKeyID = pgpKey.KeyId;
                    if (pgpKey.BitStrength != 1024)
                    {
                        Fail("failed - key strength reported incorrectly.");
                    }

                    //
                    // verify the key
                    //
                }
            }

            IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding");

            c.Init(true, pKey);

            byte[] inBytes  = Encoding.ASCII.GetBytes("hello world");
            byte[] outBytes = c.DoFinal(inBytes);

            pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

            c.Init(false, pgpPrivKey.Key);

            outBytes = c.DoFinal(outBytes);

            if (!Arrays.AreEqual(inBytes, outBytes))
            {
                Fail("decryption failed.");
            }

            //
            // encrypted message
            //
            byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o',
                            (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l',(byte)'d',  (byte)'!', (byte)'\n' };

            PgpObjectFactory pgpF = new PgpObjectFactory(encMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            Stream inLd = ld.GetDataStream();

            byte[] bytes = Streams.ReadAll(inLd);

            if (!Arrays.AreEqual(bytes, text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // signed and encrypted message
            //
            pgpF = new PgpObjectFactory(signedAndEncMessage);

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

            ld = (PgpLiteralData)pgpFact.NextPgpObject();

            bOut = new MemoryStream();

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            inLd = ld.GetDataStream();

            //
            // note: we use the DSA public key here.
            //
            ops.InitVerify(pgpPub.GetPublicKey());

            while ((ch = inLd.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
                bOut.WriteByte((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            if (!Arrays.AreEqual(bOut.ToArray(), text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // encrypt
            //
            MemoryStream cbOut            = new MemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.TripleDes, random);
            PgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey;

            cPk.AddMethod(puK);

            Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length);

            cOut.Write(text, 0, text.Length);

            cOut.Close();

            pgpF = new PgpObjectFactory(cbOut.ToArray());

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

            clear    = encP.GetDataStream(pgpPrivKey);
            outBytes = Streams.ReadAll(clear);

            if (!Arrays.AreEqual(outBytes, text))
            {
                Fail("wrong plain text in Generated packet");
            }

            //
            // use of PgpKeyPair
            //
            BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            ElGamalParameters elParams = new ElGamalParameters(p, g);

            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");

            kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));

            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral,
                                              kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;



            // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!)
            for (int pSize = 257; pSize < 264; ++pSize)
            {
                // Generate some parameters of the given size
                ElGamalParametersGenerator epg = new ElGamalParametersGenerator();
                epg.Init(pSize, 2, random);

                elParams = epg.GenerateParameters();

                kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
                kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));


                // Run a short encrypt/decrypt test with random key for the given parameters
                kp = kpg.GenerateKeyPair();

                PgpKeyPair elGamalKeyPair = new PgpKeyPair(
                    PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow);

                cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random);

                puK = elGamalKeyPair.PublicKey;

                cPk.AddMethod(puK);

                cbOut = new MemoryStream();

                cOut = cPk.Open(new UncloseableStream(cbOut), text.Length);

                cOut.Write(text, 0, text.Length);

                cOut.Close();

                pgpF = new PgpObjectFactory(cbOut.ToArray());

                encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

                encP = (PgpPublicKeyEncryptedData)encList[0];

                pgpPrivKey = elGamalKeyPair.PrivateKey;

                // Note: This is where an exception would be expected if the P size causes problems
                clear = encP.GetDataStream(pgpPrivKey);
                byte[] decText = Streams.ReadAll(clear);

                if (!Arrays.AreEqual(text, decText))
                {
                    Fail("decrypted message incorrect");
                }
            }


            // check sub key encoding

            foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
            {
                if (!pgpKey.IsMasterKey)
                {
                    byte[] kEnc = pgpKey.GetEncoded();

                    PgpObjectFactory objF = new PgpObjectFactory(kEnc);

                    // TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing
//					PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject();
//
//					pKey = k.GetKey();
//					pgpKeyID = k.KeyId;
//					if (k.BitStrength != 1024)
//					{
//						Fail("failed - key strength reported incorrectly.");
//					}
//
//					if (objF.NextPgpObject() != null)
//					{
//						Fail("failed - stream not fully parsed.");
//					}
                }
            }
        }
Beispiel #12
0
        private void TestForHighByteError(string label, int keySizeBits)
        {
            // draw a key of the size asked
            BigInteger e = BigInteger.One.ShiftLeft(16).Add(BigInteger.One);

            IAsymmetricCipherKeyPairGenerator kpGen = new RsaKeyPairGenerator();

            kpGen.Init(new RsaKeyGenerationParameters(e, new SecureRandom(), keySizeBits, 100));

            AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair();

            IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());

            // obtain a known good ciphertext
            cipher.Init(true, new ParametersWithRandom(kp.Public, new VecRand(seed)));
            byte[] m            = { 42 };
            byte[] c            = cipher.ProcessBlock(m, 0, m.Length);
            int    keySizeBytes = (keySizeBits + 7) / 8;

            if (c.Length != keySizeBytes)
            {
                Fail(label + " failed ciphertext size");
            }

            BigInteger n = ((RsaPrivateCrtKeyParameters)kp.Private).Modulus;

            // decipher
            cipher.Init(false, kp.Private);
            byte[] r = cipher.ProcessBlock(c, 0, keySizeBytes);
            if (r.Length != 1 || r[0] != 42)
            {
                Fail(label + " failed first decryption of test message");
            }

            // decipher again
            r = cipher.ProcessBlock(c, 0, keySizeBytes);
            if (r.Length != 1 || r[0] != 42)
            {
                Fail(label + " failed second decryption of test message");
            }

            // check hapazard incorrect ciphertexts
            for (int i = keySizeBytes * 8; --i >= 0;)
            {
                c[i / 8] ^= (byte)(1 << (i & 7));
                bool ko = true;
                try
                {
                    BigInteger cV = new BigInteger(1, c);

                    // don't pass in c if it will be rejected trivially
                    if (cV.CompareTo(n) < 0)
                    {
                        r = cipher.ProcessBlock(c, 0, keySizeBytes);
                    }
                    else
                    {
                        ko = false; // size errors are picked up at start
                    }
                }
                catch (InvalidCipherTextException)
                {
                    ko = false;
                }
                if (ko)
                {
                    Fail(label + " invalid ciphertext caused no exception");
                }
                c[i / 8] ^= (byte)(1 << (i & 7));
            }
        }
        /// <summary>
        /// Generates a JwtToken to use for login.
        /// </summary>
        /// <returns>The generated JWT token.</returns>
        private string GenerateJwtToken()
        {
            logger.Info("Key-pair Authentication");

            bool hasPkPath =
                session.properties.TryGetValue(SFSessionProperty.PRIVATE_KEY_FILE, out var pkPath);
            bool hasPkContent =
                session.properties.TryGetValue(SFSessionProperty.PRIVATE_KEY, out var pkContent);

            session.properties.TryGetValue(SFSessionProperty.PRIVATE_KEY_PWD, out var pkPwd);

            // Extract the public key from the private key to generate the fingerprints
            RSAParameters           rsaParams;
            String                  publicKeyFingerPrint = null;
            AsymmetricCipherKeyPair keypair = null;

            using (TextReader tr =
                       hasPkPath ? (TextReader) new StreamReader(pkPath) : new StringReader(pkContent))
            {
                try
                {
                    PemReader pr = null;
                    if (null != pkPwd)
                    {
                        IPasswordFinder ipwdf = new PasswordFinder(pkPwd);
                        pr = new PemReader(tr, ipwdf);
                    }
                    else
                    {
                        pr = new PemReader(tr);
                    }

                    object key = pr.ReadObject();
                    // Infer what the pem reader is sending back based on the object properties
                    if (key.GetType().GetProperty("Private") != null)
                    {
                        // PKCS1 key
                        keypair   = (AsymmetricCipherKeyPair)key;
                        rsaParams = DotNetUtilities.ToRSAParameters(
                            keypair.Private as RsaPrivateCrtKeyParameters);
                    }
                    else
                    {
                        // PKCS8 key
                        RsaPrivateCrtKeyParameters pk = (RsaPrivateCrtKeyParameters)key;
                        rsaParams = DotNetUtilities.ToRSAParameters(pk);
                        keypair   = DotNetUtilities.GetRsaKeyPair(rsaParams);
                    }
                    if (keypair == null)
                    {
                        throw new Exception("Unknown error.");
                    }
                }
                catch (Exception e)
                {
                    throw new SnowflakeDbException(
                              SFError.JWT_ERROR_READING_PK,
                              hasPkPath ? pkPath : "with value passed in connection string",
                              e.ToString(),
                              e);
                }
            }

            // Generate the public key fingerprint
            var publicKey = keypair.Public;

            byte[] publicKeyEncoded =
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey).GetDerEncoded();
            using (SHA256 SHA256Encoder = SHA256.Create())
            {
                byte[] sha256Hash = SHA256Encoder.ComputeHash(publicKeyEncoded);
                publicKeyFingerPrint = "SHA256:" + Convert.ToBase64String(sha256Hash);
            }

            // Generating the token
            var now = DateTime.UtcNow;

            System.DateTime dtDateTime =
                new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            long secondsSinceEpoch = (long)((now - dtDateTime).TotalSeconds);

            /*
             * Payload content
             *      iss : $accountName.$userName.$pulicKeyFingerprint
             *      sub : $accountName.$userName
             *      iat : $now
             *      exp : $now + LIFETIME
             *
             * Note : Lifetime = 120sec for Python impl, 60sec for Jdbc and Odbc
             */
            String accountUser =
                session.properties[SFSessionProperty.ACCOUNT].ToUpper() +
                "." +
                session.properties[SFSessionProperty.USER].ToUpper();
            String issuer = accountUser + "." + publicKeyFingerPrint;
            var    claims = new[] {
                new Claim(
                    JwtRegisteredClaimNames.Iat,
                    secondsSinceEpoch.ToString(),
                    System.Security.Claims.ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Sub, accountUser),
            };

            rsaProvider.ImportParameters(rsaParams);
            var token = new JwtSecurityToken(
                // Issuer
                issuer,
                // Audience
                null,
                // Subject
                claims,
                //NotBefore
                null,
                // Expires
                now.AddSeconds(60),
                //SigningCredentials
                new SigningCredentials(
                    new RsaSecurityKey(rsaProvider), SecurityAlgorithms.RsaSha256)
                );

            // Serialize the jwt token
            // Base64URL-encoded parts delimited by period ('.'), with format :
            //     [header-base64url].[payload-base64url].[signature-base64url]
            var    handler  = new JwtSecurityTokenHandler();
            string jwtToken = handler.WriteToken(token);

            return(jwtToken);
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            try
            {
                // Keypair Generator
                RsaKeyPairGenerator kpGenerator = new RsaKeyPairGenerator();
                kpGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

                // Create a keypair
                AsymmetricCipherKeyPair keys = kpGenerator.GenerateKeyPair();

                // Connect to the TPM
                Tpm2Device tpmDevice = new TbsDevice();
                tpmDevice.Connect();
                Tpm2      tpm       = new Tpm2(tpmDevice);
                AuthValue ownerAuth = new AuthValue();

                // Create a handle based on the hash of the cert thumbprint
                ushort    hashcode = (ushort)keys.GetHashCode();
                TpmHandle nvHandle = TpmHandle.NV(hashcode);

                // Clean up the slot
                tpm[ownerAuth]._AllowErrors().NvUndefineSpace(TpmHandle.RhOwner, nvHandle);

                // Export serial number, the "valid from" date (the cert will be valid for 1 year, so no need to store that date, too!), the size of the keys blob and the keys themselves
                TextWriter textWriter = new StringWriter();
                PemWriter  pemWriter  = new PemWriter(textWriter);
                pemWriter.WriteObject(keys);
                pemWriter.Writer.Flush();
                byte[] rawData = Encoding.ASCII.GetBytes(textWriter.ToString().ToCharArray());

                ushort size   = (ushort)(sizeof(long) + sizeof(long) + rawData.Length + sizeof(int) + 64);
                ushort offset = 0;

                // Define a slot for the keys, which is 64 bytes bigger than we need as we write in 64-byte chunks
                tpm[ownerAuth].NvDefineSpace(TpmHandle.RhOwner, ownerAuth, new NvPublic(nvHandle, TpmAlgId.Sha256, NvAttr.Authread | NvAttr.Authwrite, new byte[0], size));

                // Write the serial number
                tpm[ownerAuth].NvWrite(nvHandle, nvHandle, BitConverter.GetBytes(BigInteger.ProbablePrime(120, new Random()).LongValue), offset);
                offset += sizeof(long);

                // Write the "valid from" date (today) in FileTime format
                tpm[ownerAuth].NvWrite(nvHandle, nvHandle, BitConverter.GetBytes(DateTime.Today.ToFileTime()), offset);
                offset += sizeof(long);

                // Write the size of the keys
                tpm[ownerAuth].NvWrite(nvHandle, nvHandle, BitConverter.GetBytes(rawData.Length), offset);
                offset += sizeof(int);

                // Write the keys themselves (in 64-byte chunks)
                byte[] dataToWrite = new byte[64];
                int    index       = 0;
                while (index < rawData.Length)
                {
                    for (int i = 0; i < 64; i++)
                    {
                        if (index < rawData.Length)
                        {
                            dataToWrite[i] = rawData[index];
                            index++;
                        }
                        else
                        {
                            // fill the rest of the buffer with zeros
                            dataToWrite[i] = 0;
                        }
                    }

                    tpm[ownerAuth].NvWrite(nvHandle, nvHandle, dataToWrite, offset);
                    offset += 64;
                }

                tpm.Dispose();

                Console.WriteLine("Keys successfully generated and copied to TPM. Hashcode=" + hashcode.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not generate or copy keys to TPM: " + e.Message);
            }
        }
        public void TestECMqvTestVector1()
        {
            // Test Vector from GEC-2

            X9ECParameters x9 = SecNamedCurves.GetByName("secp160r1");
            var p = new ECDomainParameters(
                x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());

            IAsymmetricCipherKeyPair u1 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("0251B4496FECC406ED0E75A24A3C03206251419DC0")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("AA374FFC3CE144E6B073307972CB6D57B2A4E982", 16), p));

            IAsymmetricCipherKeyPair u2 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("03D99CE4D8BF52FA20BD21A962C6556B0F71F4CA1F")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("149EC7EA3A220A887619B3F9E5B4CA51C7D1779C", 16), p));

            IAsymmetricCipherKeyPair v1 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("0349B41E0E9C0369C2328739D90F63D56707C6E5BC")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("45FB58A92A17AD4B15101C66E74F277E2B460866", 16), p));

            IAsymmetricCipherKeyPair v2 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("02706E5D6E1F640C6E9C804E75DBC14521B1E5F3B5")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("18C13FCED9EADF884F7C595C8CB565DEFD0CB41E", 16), p));

            IBigInteger x = CalculateAgreement(u1, u2, v1, v2);

            if (x == null
                || !x.Equals(new BigInteger("5A6955CEFDB4E43255FB7FCF718611E4DF8E05AC", 16)))
            {
                Fail("MQV Test Vector #1 agreement failed");
            }
        }
        public void TestDH()
        {
            BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            DHParameters dhParams = new DHParameters(p512, g512);
            DHKeyGenerationParameters parameters = new DHKeyGenerationParameters(new SecureRandom(), dhParams);         DHKeyPairGenerator kpGen = new DHKeyPairGenerator();

            kpGen.Init(parameters);

            AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair();
            DHPublicKeyParameters   pu1  = (DHPublicKeyParameters)pair.Public;
            DHPrivateKeyParameters  pv1  = (DHPrivateKeyParameters)pair.Private;

            DHPublicKeyParameters  pu2 = new DHPublicKeyParameters(pu1.Y, pu1.Parameters);
            DHPrivateKeyParameters pv2 = new DHPrivateKeyParameters(pv1.X, pv1.Parameters);
            DHPublicKeyParameters  pu3 = new DHPublicKeyParameters(pv1.X, pu1.Parameters);
            DHPrivateKeyParameters pv3 = new DHPrivateKeyParameters(pu1.Y, pu1.Parameters);

            doTest(pu1, pu2, pu3);
            doTest(pv1, pv2, pv3);

            DHParameters pr1 = pu1.Parameters;
            DHParameters pr2 = new DHParameters(
                pr1.P, pr1.G, pr1.Q, pr1.M, pr1.L, pr1.J, pr1.ValidationParameters);
            DHParameters pr3 = new DHParameters(
                pr1.P.Add(BigInteger.Two), pr1.G, pr1.Q, pr1.M, pr1.L, pr1.J, pr1.ValidationParameters);

            doTest(pr1, pr2, pr3);

            pr3 = new DHParameters(
                pr1.P, pr1.G.Add(BigInteger.One), pr1.Q, pr1.M, pr1.L, pr1.J, pr1.ValidationParameters);

            doTest(pr1, pr2, pr3);

            pu2 = new DHPublicKeyParameters(pu1.Y, pr2);
            pv2 = new DHPrivateKeyParameters(pv1.X, pr2);

            doTest(pu1, pu2, pu3);
            doTest(pv1, pv2, pv3);

            DHValidationParameters vp1 = new DHValidationParameters(new byte[20], 1024);
            DHValidationParameters vp2 = new DHValidationParameters(new byte[20], 1024);
            DHValidationParameters vp3 = new DHValidationParameters(new byte[24], 1024);

            doTest(vp1, vp1, vp3);
            doTest(vp1, vp2, vp3);

            byte[] bytes = new byte[20];
            bytes[0] = 1;

            vp3 = new DHValidationParameters(bytes, 1024);

            doTest(vp1, vp2, vp3);

            vp3 = new DHValidationParameters(new byte[20], 2048);

            doTest(vp1, vp2, vp3);

            DHTestKeyParameters k1 = new DHTestKeyParameters(false, null);
            DHTestKeyParameters k2 = new DHTestKeyParameters(false, null);
            DHTestKeyParameters k3 = new DHTestKeyParameters(false, pu1.Parameters);

            doTest(k1, k2, k3);
        }
        public static X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, out AsymmetricKeyParameter CaPrivateKey, out AsymmetricKeyParameter CaPublicKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair    = subjectKeyPair;
            ISignatureFactory       signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            var dotNetPrivateKey = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);

            //X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());
            //x509.FriendlyName = subjectName;

            X509Certificate2 x509 = new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));

            //x509.PrivateKey = dotNetPrivateKey; set private key for x509 is not supported for now
            x509.FriendlyName = subjectName;

            CaPrivateKey = issuerKeyPair.Private;
            CaPublicKey  = subjectKeyPair.Public;

            return(x509);
        }
Beispiel #18
0
        public void doDefTest(
            IAsymmetricCipherKeyPairGenerator g,
            IBufferedCipher c1,
            IBufferedCipher c2)
        {
            //
            // a side
            //
            AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
            AsymmetricKeyParameter  aPub     = aKeyPair.Public;
            AsymmetricKeyParameter  aPriv    = aKeyPair.Private;

            //
            // b side
            //
            AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();
            AsymmetricKeyParameter  bPub     = bKeyPair.Public;
            AsymmetricKeyParameter  bPriv    = bKeyPair.Private;

            // TODO Put back in
//			//
//			// stream test
//			//
//			IEKeySpec c1Key = new IEKeySpec(aPriv, bPub);
//			IEKeySpec c2Key = new IEKeySpec(bPriv, aPub);
//
//			c1.Init(true, c1Key);
//
//			AlgorithmParameters param = c1.getParameters();
//
//			c2.Init(false, c2Key, param);
//
//			byte[] message = Hex.Decode("1234567890abcdef");
//
//			byte[] out1 = c1.DoFinal(message, 0, message.Length);
//
//			byte[] out2 = c2.DoFinal(out1, 0, out1.Length);
//
//			if (!AreEqual(out2, message))
//			{
//				Fail("stream cipher test failed");
//			}
//
//			//
//			// int DoFinal
//			//
//			int len1 = c1.DoFinal(message, 0, message.Length, out1, 0);
//
//			if (len1 != out1.Length)
//			{
//				Fail("encryption length wrong");
//			}
//
//			int len2 = c2.DoFinal(out1, 0, out1.Length, out2, 0);
//
//			if (len2 != out2.Length)
//			{
//				Fail("decryption length wrong");
//			}
//
//			if (!AreEqual(out2, message))
//			{
//				Fail("stream cipher test failed");
//			}
//
//			//
//			// int DoFinal with update
//			//
//			len1 = c1.ProcessBytes(message, 0, 2, out1, 0);
//
//			len1 += c1.DoFinal(message, 2, message.Length - 2, out1, len1);
//
//			if (len1 != out1.Length)
//			{
//				Fail("update encryption length wrong");
//			}
//
//			len2 = c2.ProcessBytes(out1, 0, 2, out2, 0);
//
//			len2 += c2.DoFinal(out1, 2, out1.Length - 2, out2, len2);
//
//			if (len2 != out2.Length)
//			{
//				Fail("update decryption length wrong");
//			}
//
//			if (!AreEqual(out2, message))
//			{
//				Fail("update stream cipher test failed");
//			}
        }
Beispiel #19
0
        public static byte[] EncodeSkinJwt(AsymmetricCipherKeyPair newKey, string username)
        {
            Skin skin = new Skin
            {
                Slim     = false,
                SkinData = Encoding.Default.GetBytes(new string('Z', 8192)),
                SkinId   = "Standard_Custom"
            };

            string skin64 = Convert.ToBase64String(skin.SkinData);


            //{
            //	"ADRole": 2,
            //	"ClientRandomId": 4670680294016914277,
            //	"CurrentInputMode": 2,
            //	"DefaultInputMode": 2,
            //	"DeviceModel": "SAMSUNG GT-P5210",
            //	"DeviceOS": 1,
            //	"GameVersion": "1.1.0.4",
            //	"GuiScale": 0,
            //	"LanguageCode": "en_US",
            //	"ServerAddress": "yodamine.com:19132",
            //	"SkinData": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADlmUf/5ZlH/+WNP//lmUf/5ZlH/+WNP//lmUf/5Y0//9iAMv/YgDL/2IAy/9iAMv/YgDL/2IAy/9iAMv/YgDL/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5Y0//+WZR//ljT//5ZlH/+WZR//ckzz/5ZlH/+idTP/YgDL/2IAy/6qJXv+qiV7/qole/6qJXv/YgDL/2IAy/wAAAAAAAAAAAAAAAAAAA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tr/2FhYf9cXFz/UlJS/01NTf9NTU3/SkpK/1BQUP9QUFD/SkpK/+/av//s1Lj/79q//+zUuP/y3cL/8t/I//Ldwv/v2r//7NS4/+zUuP/v2r//8t3C//LfyP/y38j/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8/P/8/Pz//Pz8//1xcXP9jY2P/cHBw/3BwcP9jY2P/XFxc/z8/P/8/Pz//Pz8//0hISP9MTEz/TExM/0hISP/v2r//69Oz/+zUuP/s1Lj/8t/I//Ldwv/y3cL/7NS4/+/av//s1Lj/7NS4//Ldwv/y38j/8t/I/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
            //	"SkinId": "Standard_Alex",
            //	"TenantId": "",
            //  "ThirdPartyName": "gurunx",
            //	"UIProfile": 1
            //}

            string skinData = $@"
{{
	""CapeData"": """",
	""ADRole"": 0,
	""ClientRandomId"": {new Random().Next()},
	""CurrentInputMode"": 1,
	""DefaultInputMode"": 1,
	""DeviceModel"": ""MINET CLIENT"",
	""DeviceOS"": 7,
	""GameVersion"": ""{McpeProtocolInfo.GameVersion}"",
	""IsEduMode"": {Config.GetProperty("EnableEdu", false).ToString().ToLower()},
	""GuiScale"": 0,
	""LanguageCode"": ""en_US"",
	""PlatformOfflineId"": """",
	""PlatformOnlineId"": """",
	""SelfSignedId"": ""{Guid.NewGuid().ToString()}"",
	""ServerAddress"": ""yodamine.com:19132"",
	""SkinData"": ""{skin64}"",
	""SkinId"": ""{skin.SkinId}"",
	""TenantId"": ""38dd6634-1031-4c50-a9b4-d16cd9d97d57"",
	""ThirdPartyName"": ""{username}"",
	""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));
        }
        static void Main(string[] args)
        {
            //web site: https://www.youtube.com/watch?v=4iPzIEXC7a8

            string SourceData;

            byte[] tmpSource;
            byte[] tmpHash;

            //enter the any text
            Console.WriteLine("Enter any text: ");

            //var _database = DataBase.meuTexto(); //database
            //var _iOS = iOS.meuTexto();
            var _ws = WebApi.meuTexto();

            SourceData = _ws;//Console.ReadLine();

            //create byte array from source data
            tmpSource = ASCIIEncoding.ASCII.GetBytes(SourceData);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Key pairs are generating ... please wait for few minutes ... ");
            Console.WriteLine();

            //RSAKeyPairGeneration
            RsaKeyPairGenerator rsaKeyPairGen = new RsaKeyPairGenerator();

            rsaKeyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair();

            //extrating the private key from the pair
            RsaKeyParameters PrivateKey = (RsaKeyParameters)keyPair.Private;
            RsaKeyParameters PublicKey  = (RsaKeyParameters)keyPair.Public;

            //print the public key in pem format
            TextWriter textWriter1 = new StringWriter();
            PemWriter  pemWriter1  = new PemWriter(textWriter1);

            pemWriter1.WriteObject(PublicKey);
            pemWriter1.Writer.Flush();
            string print_publicKey = textWriter1.ToString();

            Console.WriteLine("Public Key is: {0}", print_publicKey);
            Console.WriteLine();

            //generation of digital signature sha-512
            ISigner sign = SignerUtilities.GetSigner(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id);

            sign.Init(true, PrivateKey);
            sign.BlockUpdate(tmpSource, 0, tmpSource.Length);
            byte[] signature = sign.GenerateSignature();

            Console.WriteLine();
            Console.WriteLine("The digital signature is: ");
            Console.WriteLine(ByteArrayToString(signature));
            Console.WriteLine();

            //verification of the digital signature
            ISigner sign1 = SignerUtilities.GetSigner(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id);

            sign1.Init(false, PublicKey);
            sign1.BlockUpdate(tmpSource, 0, tmpSource.Length);
            bool status = sign1.VerifySignature(signature);

            Console.WriteLine();
            Console.WriteLine("Status of the digital signature: " + " ");
            if (status == true)
            {
                Console.WriteLine("Signature is valid");
                Console.WriteLine();
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Signature is not valid");
                Console.WriteLine();
                Console.ReadLine();
            }
            Console.WriteLine("Please click enter two times");
            Console.ReadLine();
        }
Beispiel #21
0
        /// <summary>
        /// Read CA private key file from .key or pfx file
        /// Read data from certificate request file .csr
        /// Generate signed certificate request file .cer
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GenerateCerFile(string certRequestFile,
                                           string privateKeyFile,
                                           string generateSignedCertificateFile,
                                           string password, string friendlyName,
                                           DateTime startDate, DateTime endDate)
        {
            #region LoadCertificate

            // read public & private key from file
            AsymmetricKeyParameter privateKey = null;
            AsymmetricKeyParameter publicKey  = null;

            System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate = null;
            Org.BouncyCastle.X509.X509Certificate issuerCertificateX509 = null;

            // Ovo NE radi
            //issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
            //        privateKeyFile,
            //        password
            //        );

            // Ovo RADI
            issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                privateKeyFile,
                password,
                System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
                );

            // This doesn't work for selfsign certificate
            //bool isOK = issuerCertificate.Verify();

            bool     isHasPrivateKey = issuerCertificate.HasPrivateKey;
            DateTime noAfter         = issuerCertificate.NotAfter;
            DateTime noBefore        = issuerCertificate.NotBefore;
            X509ExtensionCollection x509extensions = issuerCertificate.Extensions;

            int errorNum = 0;
            X509CertificateParser parser = new X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(issuerCertificate.RawData);
            BasicConstraints basicConstraints = null;
            bool             isCa             = false;
            Asn1OctetString  str = bouncyCertificate.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
            if (str != null)
            {
                basicConstraints = BasicConstraints.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(str));
                if (basicConstraints != null)
                {
                    isCa = basicConstraints.IsCA();
                }
            }

            if (!isCa)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Loaded CA file: " + privateKeyFile + " IS NOT CA authority certificate file!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            // This doesn't work for selfsign certificate
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "File with CA certificate NOT valid." + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            if (!isHasPrivateKey)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate DOES NOT have a private key." + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noBefore > startDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate start date: " + startDate.ToLocalTime() + " DOES NOT valid value. Certificate start date is: " + noBefore.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noAfter < endDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate end date: " + endDate.ToLocalTime() + " DOES NOT valid value. Certificate end date is: " + noAfter.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            if (errorNum > 0)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate has error!!!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                return;
            }
            bool isOk = issuerCertificate.Verify();

            AsymmetricCipherKeyPair issuerKeyPairTmp = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
            privateKey = issuerKeyPairTmp.Private;
            publicKey  = issuerKeyPairTmp.Public;

            issuerCertificateX509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(issuerCertificate.GetRawCertData());
            issuerCertificateX509.Verify(publicKey);

            Org.BouncyCastle.X509.X509Certificate x509 = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCertificate);
            x509.Verify(publicKey);
            x509.CheckValidity(startDate);

            #endregion

            // Read certificate request .csr file
            Pkcs10CertificationRequest cerRequest = null;
            try
            {
                String       input_data = File.ReadAllText(certRequestFile);
                StringReader sr         = new StringReader(input_data);
                PemReader    pr         = new PemReader(sr);
                cerRequest = (Pkcs10CertificationRequest)pr.ReadObject();

                tbOutputMessageBox.Text += "Verify file with certificate request : " + certRequestFile + "\n";
                bool requestIsOK = cerRequest.Verify();
                if (requestIsOK)
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " is OK." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " NOT valid." + "\n";
                    return;
                }
            }
            catch (Exception ex)
            {
                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR reading certificate request file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            Org.BouncyCastle.X509.X509Certificate genCert = GenerateSignedCertificate(
                cerRequest,
                x509,
                issuerKeyPairTmp,
                startDate, endDate);

            try
            {
                File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());
                tbOutputMessageBox.Text += "Certificate file: " + generateSignedCertificateFile + " sucessfully saved." + "\n";

                signedRequestFileNamePath = generateSignedCertificateFile;
                btnContinue.IsEnabled     = true;
            }
            catch (Exception)
            {
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }

            #region Public Key
            //try
            //{
            //    var store = new Pkcs12Store();
            //    string friendlyName1 = issuerCertificateX509.SubjectDN.ToString();
            //    var certificateEntry = new X509CertificateEntry(issuerCertificateX509);
            //    store.SetCertificateEntry(friendlyName1, certificateEntry);
            //    store.SetKeyEntry(friendlyName1, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            //    var stream = new MemoryStream();
            //    var random1 = GetSecureRandom();
            //    store.Save(stream, "password".ToCharArray(), random1);

            //    //Verify that the certificate is valid.
            //    var convertedCertificate = new X509Certificate2(stream.ToArray(), "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //    //Write the file.
            //    File.WriteAllBytes(generateSignedCertificateFile, stream.ToArray());

            //    File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());

            //    //using (TextWriter tw = new StreamWriter(outputPublicKeyName))
            //    //{
            //    //    PemWriter pw = new PemWriter(tw);
            //    //    pw.WriteObject(subjectKeyPair.Public);
            //    //    tw.Flush();
            //    //}

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}

            //StringBuilder publicKeyStrBuilder = new StringBuilder();
            //PemWriter publicKeyPemWriter = new PemWriter(new StringWriter(publicKeyStrBuilder));
            //publicKeyPemWriter.WriteObject(genCert.GetPublicKey());
            //publicKeyPemWriter.Writer.Flush();

            //string publicKey = publicKeyStrBuilder.ToString();
            //try
            //{
            //    using (TextWriter tw = new StreamWriter(generateSignedCertificateFile))
            //    {
            //        PemWriter pw = new PemWriter(tw);
            //        pw.WriteObject(genCert.GetPublicKey());
            //        tw.Flush();
            //    }

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}
            #endregion Public Key
        }
        private static void RsaKeyGeneratorTest()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);

            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和私钥
            AsymmetricKeyParameter publicKey  = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
            {
                Console.WriteLine("failed key generation (1024) length test");
            }
            savetheKey(publicKey, privateKey);



            //一个测试……………………
            //输入,十六进制的字符串,解码为byte[]
            //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
            //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input);
            string input = "popozh RSA test";

            byte[] testData = Encoding.UTF8.GetBytes(input);
            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();
            //公钥加密
            //从保存在本地的磁盘文件中读取公钥
            Asn1Object             aobject       = Asn1Object.FromStream(new FileStream(pubKeyFile, FileMode.Open, FileAccess.Read)); //a.puk??
            SubjectPublicKeyInfo   pubInfo       = SubjectPublicKeyInfo.GetInstance(aobject);
            AsymmetricKeyParameter testpublicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
            FileStream             fs;

            engine.Init(true, testpublicKey);
            try
            {
                //Console.WriteLine("加密前:" + Convert.ToBase64String(testData) + Environment.NewLine);
                testData = engine.ProcessBlock(testData, 0, testData.Length);
                Console.WriteLine("加密完成!" + Environment.NewLine);
                fs = new FileStream(ecyFile, FileMode.Create, FileAccess.Write);
                fs.Write(testData, 0, testData.Length);
                fs.Close();
                Console.WriteLine("保存密文成功" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString());
            }
            //私钥解密
            //获取加密的私钥,进行解密,获得私钥
            fs = new FileStream(ecyFile, FileMode.Open, FileAccess.Read);
            byte[] anothertestdata = new byte[1024];
            fs.Read(anothertestdata, 0, anothertestdata.Length);
            fs.Close();
            Asn1Object aobj = Asn1Object.FromStream(new FileStream(priKeyFile, FileMode.Open, FileAccess.Read));   //a.pvk??
            EncryptedPrivateKeyInfo enpri = EncryptedPrivateKeyInfo.GetInstance(aobj);

            char[]                 password          = "******".ToCharArray();
            PrivateKeyInfo         priKey            = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enpri); //解密
            AsymmetricKeyParameter anotherprivateKey = PrivateKeyFactory.CreateKey(priKey);                         //私钥

            engine.Init(false, anotherprivateKey);
            try
            {
                anothertestdata = engine.ProcessBlock(anothertestdata, 0, testData.Length);
                Console.WriteLine("解密后密文为:" + Encoding.UTF8.GetString(anothertestdata) + Environment.NewLine);
            }
            catch (Exception e)
            {
                Console.WriteLine("failed - exception " + e.ToString());
            }

            Console.Read();
        }
Beispiel #23
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="csr"></param>
        /// <param name="rootCert"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        private Org.BouncyCastle.X509.X509Certificate GenerateSignedCertificate(
            Pkcs10CertificationRequest csr,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            //List<ExtensionsItem> extensions = null;

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(rootCert.SubjectDN);

            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(csr.GetPublicKey());

            var sigAlg  = csr.Signature;
            var sigAlg1 = csr.SignatureAlgorithm;

            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");


            // Add certificate extensions
            Asn1Set attributes = csr.GetCertificationRequestInfo().Attributes;

            if (attributes != null)
            {
                for (int i = 0; i != attributes.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(attributes[i]);

                    if (attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions1 = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier oid in extensions1.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions1.GetExtension(oid);

                            // !!! NOT working !!!
                            //certGen.AddExtension(oid, ext.IsCritical, ext.Value);

                            //OK
                            certGen.AddExtension(oid, ext.IsCritical, ext.Value, true);
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Check if generated certificate file is valid, plase wait ..." + "\n";
                issuedCert.CheckValidity(DateTime.UtcNow);
                tbOutputMessageBox.Text += "Generate certificate file is valid." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Verify generated certificate file, plase wait ..." + "\n";
                issuedCert.Verify(issuerKeyPair.Public);
                tbOutputMessageBox.Text += "Generate certificate file verification is OK." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            return(issuedCert);
        }
Beispiel #24
0
 public GA(AsymmetricCipherKeyPair keys) => this.keys = keys;
Beispiel #25
0
        private static Pkcs10CertificationRequest CreatePKCS10ForComputer(string challengePassword, AsymmetricCipherKeyPair rsaKeyPair)
        {
            //            GenerateSelfSignedCertificate("CN=" + LDAPTools.QuoteRDN(fqdn), out RSA algRSA, out CertificateRequest req, out X509Certificate2 selfSignedCert);

            AsnX509.X509ExtensionsGenerator extensions = new AsnX509.X509ExtensionsGenerator();

            ISet <string> sanDNSCollection = new HashSet <string>(4);

            string hostName = Dns.GetHostName();

            sanDNSCollection.Add(hostName);
            string fqdn = Dns.GetHostEntry(hostName).HostName;

            sanDNSCollection.Add(fqdn);

#if !DEBUG
            Domain computerDomain = Domain.GetComputerDomain();
            sanDNSCollection.Add(computerDomain.Name);

            string NetBIOSDomain = GetNetbiosDomainName(computerDomain.Name);
            if (!string.IsNullOrEmpty(NetBIOSDomain))
            {
                sanDNSCollection.Add(NetBIOSDomain);
            }
#endif // !DEBUG

            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
            foreach (string dnsName in sanDNSCollection)
            {
                sanBuilder.AddDnsName(dnsName);
            }
            System.Security.Cryptography.X509Certificates.X509Extension sanExtension = sanBuilder.Build();
            extensions.AddExtension(new DerObjectIdentifier(sanExtension.Oid.Value), sanExtension.Critical, sanExtension.RawData);

            BCPkcs.AttributePkcs extensionRequest = new BCPkcs.AttributePkcs(BCPkcs.PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(extensions.Generate()));

            BCPkcs.AttributePkcs attrPassword = new BCPkcs.AttributePkcs(BCPkcs.PkcsObjectIdentifiers.Pkcs9AtChallengePassword, new DerSet(new DerPrintableString(challengePassword)));

            Pkcs10CertificationRequest request = new Pkcs10CertificationRequest(
                "SHA256WITHRSA",
                new AsnX509.X509Name(new DerObjectIdentifier[] { AsnX509.X509Name.CN }, new string[] { fqdn }),
                rsaKeyPair.Public,
                new DerSet(extensionRequest, attrPassword),
                rsaKeyPair.Private
                );
            return(request);
        }
        private static Org.BouncyCastle.X509.X509Certificate GenerateCertificate(SecureRandom random, string subjectDN, AsymmetricCipherKeyPair subjectKeyPair,
                                                                                 BigInteger subjectSerialNumber, IEnumerable <string> subjectAlternativeNames,
                                                                                 string issuerDN, AsymmetricCipherKeyPair issuerKeyPair, int keyUsages,
                                                                                 List <KeyPurposeID> extendedKeyUsages, int yearsValid, string signatureAlgorithmName)
        {
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(subjectSerialNumber);
            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithmName, issuerKeyPair.Private, random);
            var issuerDN509      = new X509Name(issuerDN);

            certificateGenerator.SetIssuerDN(issuerDN509);

            var subjectDN509 = new X509Name(subjectDN);

            certificateGenerator.SetSubjectDN(subjectDN509);

            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(yearsValid);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            var subjectKeyIdentifierExtension = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public));

            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension);

            certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            // http://tools.ietf.org/html/rfc5280#section-4.2.1.3
            if (keyUsages > 0)
            {
                certificateGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(keyUsages));
            }

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedKeyUsages.ToArray()));
            AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames);

            var certificate = certificateGenerator.Generate(signatureFactory);

            return(certificate);
        }
Beispiel #27
0
        private static Pkcs10CertificationRequest CreatePKCS10(string sCN, string challengePassword, AsymmetricCipherKeyPair rsaKeyPair)
        {
            BCPkcs.AttributePkcs attrPassword = new BCPkcs.AttributePkcs(BCPkcs.PkcsObjectIdentifiers.Pkcs9AtChallengePassword, new DerSet(new DerPrintableString(challengePassword)));

            Pkcs10CertificationRequest request = new Pkcs10CertificationRequest(
                "SHA256WITHRSA",
                new AsnX509.X509Name(new DerObjectIdentifier[] { AsnX509.X509Name.CN }, new string[] { sCN }),
                rsaKeyPair.Public,
                new DerSet(attrPassword),
                rsaKeyPair.Private
                );

            return(request);
        }
Beispiel #28
0
        public SimpleTestResult EncodeRecodePublicKey()
        {
            DerObjectIdentifier       oid          = ECGost3410NamedCurves.GetOid("Tc26-Gost-3410-12-512-paramSetA");
            ECNamedDomainParameters   ecp          = new ECNamedDomainParameters(oid, ECGost3410NamedCurves.GetByOid(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));
        }
Beispiel #29
0
        //@TODO: Generates a seemingly valid CSR but the Apple website doesn't accept this one (there is a context dependant 0 missing and a null missing compared to Keychain or OpenSSL generated ones, so the files aren't structurally identical)
        private void GenerateSigningRequestViaBouncyCastle(string TargetCertRequestFileName, AsymmetricCipherKeyPair KeyPair)
        {
            // Construct the request subject
            Hashtable Attributes = new Hashtable();

            Attributes.Add(X509Name.EmailAddress, EMailEditBox.Text);
            Attributes.Add(X509Name.CN, CommonNameEditBox.Text);
            Attributes.Add(X509Name.C, System.Globalization.RegionInfo.CurrentRegion.TwoLetterISORegionName);

            X509Name Subject = new X509Name(new ArrayList(Attributes.Keys), Attributes);

            // Generate a certificate signing request
            Pkcs10CertificationRequest CSR = new Pkcs10CertificationRequest(
                "SHA1withRSA",
                Subject,
                KeyPair.Public,
                null,
                KeyPair.Private);

            // Save the CSR to disk
            File.WriteAllBytes(TargetCertRequestFileName, CSR.GetEncoded());
        }
Beispiel #30
0
        public Org.BouncyCastle.X509.X509Certificate GenerateCertificate(SecureRandom random,
                                                                         string subjectName,
                                                                         AsymmetricCipherKeyPair subjectKeyPair,
                                                                         BigInteger subjectSerialNumber,
                                                                         string[] subjectAlternativeNames,
                                                                         string issuerName,
                                                                         AsymmetricCipherKeyPair issuerKeyPair,
                                                                         BigInteger issuerSerialNumber,
                                                                         bool isCertificateAuthority,
                                                                         KeyPurposeID[] usages)
        {
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(subjectSerialNumber);

            // Set the signature algorithm. This is used to generate the thumbprint which is then signed
            // with the issuer's private key. We'll use SHA-256, which is (currently) considered fairly strong.
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            var issuerDN = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);

            // Note: The subject can be omitted if you specify a subject alternative name (SAN).
            var subjectDN = new X509Name(subjectName);

            certificateGenerator.SetSubjectDN(subjectDN);

            // Our certificate needs valid from/to values.
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(20);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // The subject's public key goes in the certificate.
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            AddAuthorityKeyIdentifier(certificateGenerator, issuerDN, issuerKeyPair, issuerSerialNumber);
            AddSubjectKeyIdentifier(certificateGenerator, subjectKeyPair);
            AddBasicConstraints(certificateGenerator, isCertificateAuthority);

            if (usages != null && usages.Any())
            {
                AddExtendedKeyUsage(certificateGenerator, usages);
            }

            if (subjectAlternativeNames != null && subjectAlternativeNames.Any())
            {
                AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames);
            }



            // The certificate is signed with the issuer's private key.
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            return(certificate);
        }
Beispiel #31
0
        private void GenerateSigningRequestViaOpenSSL(string TargetCertRequestFileName, AsymmetricCipherKeyPair KeyPair)
        {
            // We expect openssl.exe to exist in the same directory as iPhonePackager
            string OpenSSLPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\openssl.exe";

            if (!File.Exists(OpenSSLPath))
            {
                MessageBox.Show("A version of OpenSSL is required to generate certificate requests.  Please place OpenSSL.exe in Binaries\\DotNET\\IOS", Config.AppDisplayName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string EffectiveBuildPath = (Program.GameName.Length > 0) ? Config.BuildDirectory : Path.GetFullPath(".");

            // Create a temporary file to write the key pair out to (in a format that OpenSSL understands)
            string     KeyFileName = Path.GetTempFileName();
            TextWriter KeyWriter   = new StreamWriter(KeyFileName);

            PemWriter KeyWriterPEM = new PemWriter(KeyWriter);

            KeyWriterPEM.WriteObject(KeyPair);
            KeyWriter.Close();

            // Create a temporary file containing the configuration settings to drive OpenSSL
            string     ConfigFileName = Path.GetTempFileName();
            TextWriter ConfigFile     = new StreamWriter(ConfigFileName);

            ConfigFile.WriteLine("[ req ]");
            ConfigFile.WriteLine("distinguished_name     = req_distinguished_name");
            ConfigFile.WriteLine("prompt                 = no");

            ConfigFile.WriteLine("[ req_distinguished_name ]");
            ConfigFile.WriteLine("emailAddress           = {0}", EMailEditBox.Text);
            ConfigFile.WriteLine("commonName             = {0}", CommonNameEditBox.Text);
            ConfigFile.WriteLine("countryName            = {0}", System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName);

            ConfigFile.Close();

            // Invoke OpenSSL to generate the certificate request
            Program.Log("Running OpenSSL to generate certificate request...");

            string ResultsText;
            string Executable = OpenSSLPath;
            string Arguments  = String.Format("req -new -nodes -out \"{0}\" -key \"{1}\" -config \"{2}\"",
                                              TargetCertRequestFileName, KeyFileName, ConfigFileName);

            Utilities.RunExecutableAndWait(Executable, Arguments, out ResultsText);

            Program.Log(ResultsText);

            if (!File.Exists(TargetCertRequestFileName))
            {
                Program.Error("... Failed to generate certificate request");
            }
            else
            {
                Program.Log("... Successfully generated certificate request '{0}'", TargetCertRequestFileName);
            }

            // Clean up the temporary files we created
            File.Delete(KeyFileName);
            File.Delete(ConfigFileName);
        }
        public void TestECMqvTestVector2()
        {
            // Test Vector from GEC-2

            X9ECParameters x9 = SecNamedCurves.GetByName("sect163k1");
            var p = new ECDomainParameters(
                x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());

            IAsymmetricCipherKeyPair u1 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("03037D529FA37E42195F10111127FFB2BB38644806BC")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("03A41434AA99C2EF40C8495B2ED9739CB2155A1E0D", 16), p));

            IAsymmetricCipherKeyPair u2 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("02015198E74BC2F1E5C9A62B80248DF0D62B9ADF8429")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("032FC4C61A8211E6A7C4B8B0C03CF35F7CF20DBD52", 16), p));

            IAsymmetricCipherKeyPair v1 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("03072783FAAB9549002B4F13140B88132D1C75B3886C")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("57E8A78E842BF4ACD5C315AA0569DB1703541D96", 16), p));

            IAsymmetricCipherKeyPair v2 = new AsymmetricCipherKeyPair(
                new ECPublicKeyParameters(
                    p.Curve.DecodePoint(Hex.Decode("03067E3AEA3510D69E8EDD19CB2A703DDC6CF5E56E32")), p),
                new ECPrivateKeyParameters(
                    new BigInteger("02BD198B83A667A8D908EA1E6F90FD5C6D695DE94F", 16), p));

            IBigInteger x = CalculateAgreement(u1, u2, v1, v2);

            if (x == null
                || !x.Equals(new BigInteger("038359FFD30C0D5FC1E6154F483B73D43E5CF2B503", 16)))
            {
                Fail("MQV Test Vector #2 agreement failed");
            }
        }
Beispiel #33
0
 /// <summary>
 /// Setting the keyPair with a <see cref="AsymmetricCipherKeyPair"/>.
 /// To get this object from a StreamReader, use <see cref="Yoti.Auth.CryptoEngine.LoadRsaKey(StreamReader)"/>.
 /// </summary>
 /// <param name="keyPair"></param>
 /// <returns><see cref="SandboxClientBuilder"/></returns>
 public SandboxClientBuilder WithKeyPair(AsymmetricCipherKeyPair keyPair)
 {
     _keyPair = keyPair;
     return(this);
 }