/// <summary> /// Constructor from an algorithm and an encoding of a PrivateKeyInfo object containing a NewHope private key. /// </summary> /// <param name="alg">Algorithm marker to associate with the key.</param> /// <param name="encoding">An encoding of a PrivateKeyInfo object.</param> public AsymmetricNHPrivateKey(Algorithm alg, byte[] encoding) : this(alg, PrivateKeyInfo.GetInstance(encoding)) { }
public static void Main1(string[] args) { //公钥和密钥的生成,并加密解密测试 //RsaKeyGeneratorTest(); //done!!!!! byte[] msg = Encoding.UTF8.GetBytes("abcdefg"); string priKeyString = File.ReadAllText(@"E:\OwenProject\RSA\pc8_bc.pem"); string pubKeyString = File.ReadAllText(@"E:\OwenProject\RSA\pc8_bc_pub.pem"); using (TextReader priReader = new StringReader(priKeyString) , pubReader = new StringReader(pubKeyString)) { PemReader pemReader = new PemReader(priReader); var obj = pemReader.ReadObject(); var pri = obj as RsaPrivateCrtKeyParameters; //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //RSAParameters p = new RSAParameters(); //p.DP = pri.DP.ToByteArray(); //p.DQ = pri.DQ.ToByteArray(); //p.Exponent = pri.Exponent.ToByteArray(); //p.P = pri.P.ToByteArray(); //p.Q = pri.Q.ToByteArray(); //p.Modulus = pri.Modulus.ToByteArray(); //p.D = pri.PublicExponent.ToByteArray(); //p.InverseQ = pri.QInv.ToByteArray(); //rsa.ImportParameters(p); PemReader pemReaderPub = new PemReader(pubReader); var objPub = pemReaderPub.ReadObject(); var pub = objPub as RsaKeyParameters; //AsymmetricCipherKeyPair kp = new AsymmetricCipherKeyPair(pri, pub); RsaDigestSigner signer = new RsaDigestSigner(new Sha1Digest()); signer.Init(true, pri); signer.BlockUpdate(msg, 0, msg.Length); byte[] sig = signer.GenerateSignature(); Console.WriteLine(Convert.ToBase64String(sig)); signer.Init(false, pub); signer.BlockUpdate(msg, 0, msg.Length); bool valid = signer.VerifySignature(sig); Console.WriteLine(valid); } var priKeyContent = Convert.FromBase64String(@"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKko+TE1xJaRoRm/UrNIoWDejYYPdDurNZe28pXFrRWTyFFPx9ABOx6XduSkbxbmCnh3bqE5ytlpKmZjxVCV74wT9RYMzkmERlBhI55aK6deKNnRS8OluiNyJybT3pxCzKe+daj3P4LgjQLe3d0Jn+bWUT2L0iA/TCdDt6ZLZywVAgMBAAECgYBY7Y5bPW30zehIVdlPIQ6dk0IJSRSMzcvlzyqma/47Cq7TeEKN6ie/RFcfigZQnmzAueCx52TpeKzumOLBI6GDQgnSBx8RVPjx/p8XNGUxw4UQiUG+EW7iNqLEKKKtnwfjYNqFcNAsn1b8CCMORozIwYLhn5ihkBiz10ITQURQoQJBAOBxhfpDYFNhlYHuP3qn7VqKZCzzbAfT6OOuc8GoEJvHeBnKczFrUzMmbiberVn5g/l7rJ9rfakY32f5KYP73XkCQQDA8Z03nqKhqaxdEG2JgStcGgMT1htkWeSmUNoKaY+SBor3BVLrd30VZGp51zzAcTY9pdUG7PQXystxn6Htskh9AkEAhnk+Dp4DvrF/BGQcwH6QpWi5cH1AQshihtflHyh1GwC+IqW7suZc6Q6jfMJ6Fqh6vCWvXaznk0MFx6PvjdZ/8QJBAIZTL7sbK+oUsDUSTNAgJ0m1qlLTCrrwgmjvfP0mxJdLCtAy2qmnxGNyR1aP7HGl37dHjmmF6eHug3iVRCyxpBkCQATsf3oAPErQ0AT2wB0Uof6uv0x+/6r1q0cuR/R3Htd3Sz9GIx+4v79p41DBcSMyr2fubtXp6WiHSlvseiKigWU="); var pubKeyContent = Convert.FromBase64String(@"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpKPkxNcSWkaEZv1KzSKFg3o2GD3Q7qzWXtvKVxa0Vk8hRT8fQATsel3bkpG8W5gp4d26hOcrZaSpmY8VQle+ME/UWDM5JhEZQYSOeWiunXijZ0UvDpbojcicm096cQsynvnWo9z+C4I0C3t3dCZ/m1lE9i9IgP0wnQ7emS2csFQIDAQAB"); //var priKeyContent = Convert.FromBase64String(@"MIICWwIBAAKBgQDsQIuN+M/x9grPYectc3Ye5rboKWT12w9KcSWLgdRlUg9IGe6oDYj/CEGh0rJi4pijlRRY06Ri8MLkn76T/sYYXHuYSzVgAaolhD1Fpv0NwQBBGwWhogz/FF1qhW2dMQiMlBlQjp6jblzbJwnPAg9mESvywj8h03KNG3VnPAhCMwIDAQABAoGAfJsWgA0JcG77CKJ0ke5iEK5TLmQW0e12RSckTE5vvfjoAnla/NwWs5yhMT61w54ML8tDbg5Cl8SwpnDyzZAE3nTX86+oqRUDdJV96YOR2gti6lcfiZYd6qqPgnbZ4KQmcE+LRMpWhnL9zoAdg4kSorHP/nl8UfaRZQqhILg6G4ECQQD/8EOpEq/+M011yLlXMOO496/ckCrfm08DAw9vl0K5FVBMD9Fsd31/7pZh7Um7dqCabaNsYYorbIsffMQXB/6hAkEA7E8SClZJtTE+hUK2Vn9SNTQlofuztui2kRt0lt0+rjqgh+GH3FkPQeVVTQ7dxkq2aUntkEtELso+RRkYgbg0UwJACFF0wX/7/FUKhXN6opzSKebS7mY5Hn9buAtXaxcNchqBO5egBNh1Wb0VYiVmKhOW8K3zi8g3x2WFuAZEEUOPQQJAGTyMiawTbRVYPvUT8gLg7aunBTiTRcpujOqotd/k7Mh4EmrkjoS4W2o5hOQ8jQu3lWD+zPUsz+5rXgfDFT9t3wJACdFWlzj1TC64f9bNo7I2n1S+xWn1Rm/z0e+fVq2n7sbtVtaYQY1HSXPOuDgCKMPcx5Fp1EuhzDvnxIaPdUXzyQ=="); var asn1Seq = Asn1Sequence.GetInstance(priKeyContent); if (asn1Seq is DerSequence) { asn1Seq = (Asn1Sequence)asn1Seq; } var ppriv = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1Seq)) as AsymmetricKeyParameter; var ppubl = PublicKeyFactory.CreateKey((pubKeyContent)); RsaDigestSigner signer1 = new RsaDigestSigner(new Sha1Digest()); signer1.Init(true, ppriv); signer1.BlockUpdate(msg, 0, msg.Length); byte[] sig1 = signer1.GenerateSignature(); Console.WriteLine(Convert.ToBase64String(sig1)); signer1.Init(false, ppubl); signer1.BlockUpdate(msg, 0, msg.Length); bool valid2 = signer1.VerifySignature(sig1); Console.WriteLine(valid2); }
public Pkcs8EncryptedPrivateKeyInfoBuilder(PrivateKeyInfo privateKeyInfo) { this.privateKeyInfo = privateKeyInfo; }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } if (password == null) { throw new ArgumentNullException("password"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool unmarkedKey = false; bool wrongPkcs12Zero = false; if (bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); IList chain = Platform.CreateArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; if (oid.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets = ((Asn1OctetString)ci.Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // IDictionary attributes = Platform.CreateHashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { unmarkedKey = true; keys["unmarked"] = pkcs12Key; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else { Debug.WriteLine("extra " + b.BagID); Debug.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { EncryptedData d = EncryptedData.GetInstance(ci.Content); byte[] octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // IDictionary attributes = Platform.CreateHashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { PrivateKeyInfo privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); // // set the attributes on the key // string alias = null; Asn1OctetString localId = null; IDictionary attributes = Platform.CreateHashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]); Asn1Set attrSet = Asn1Set.GetInstance(sq[1]); Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { Debug.WriteLine("extra " + b.BagID); Debug.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else { Debug.WriteLine("extra " + oid); Debug.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content)); } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in chain) { CertBag cb = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)cb.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // IDictionary attributes = Platform.CreateHashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]); Asn1Set attrSet = Asn1Set.GetInstance(sq[1]); if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes); chainCerts[certId] = pkcs12Cert; if (unmarkedKey) { if (keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); keyCerts[name] = pkcs12Cert; object temp = keys["unmarked"]; keys.Remove("unmarked"); keys[name] = temp; } } else { if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); keyCerts[name] = pkcs12Cert; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = pkcs12Cert; } } } }
/** * decrypt the content and return an input stream. */ public override CmsTypedStream GetContentStream( // Key key) ICipherParameters key) { if (!(key is AsymmetricKeyParameter)) { throw new ArgumentException("KeyAgreement requires asymmetric key", "key"); } AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)key; if (!privKey.IsPrivate) { throw new ArgumentException("Expected private key", "key"); } try { OriginatorPublicKey origK = _info.Originator.OriginatorKey; PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey); SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(privInfo.AlgorithmID, origK.PublicKey.GetBytes()); AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(pubInfo); string wrapAlg = DerObjectIdentifier.GetInstance( Asn1Sequence.GetInstance(_keyEncAlg.Parameters)[0]).Id; IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf( _keyEncAlg.ObjectID, wrapAlg); agreement.Init(privKey); BigInteger wKeyNum = agreement.CalculateAgreement(pubKey); KeyParameter wKey = ParameterUtilities.CreateKeyParameter( wrapAlg, wKeyNum.ToByteArrayUnsigned()); IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg); keyCipher.Init(false, wKey); AlgorithmIdentifier aid = _encAlg; string alg = aid.ObjectID.Id; byte[] encryptedKey = _encryptedKey.GetOctets(); KeyParameter sKey = ParameterUtilities.CreateKeyParameter( alg, keyCipher.Unwrap(encryptedKey, 0, encryptedKey.Length)); return(GetContentFromSessionKey(sKey)); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (Exception e) { throw new CmsException("originator key invalid.", e); } }
public EncKeyWithID(PrivateKeyInfo privKeyInfo, DerUtf8String str) { this.privKeyInfo = privKeyInfo; this.identifier = str; }
/// <summary> /// Generates a certificate signed by the CA /// </summary> /// <param name="subjectName"></param> /// <param name="issuerName"></param> /// <param name="issuerPrivKey"></param> /// <param name="keyStrength"></param> /// <returns></returns> public static X509Certificate2 GenerateCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 1024) { // Generating Random Numbers CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivKey, random); // 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 = new X509Name(issuerName); 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; var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Generating the Certificate AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair; // selfsign certificate Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory); // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
// Method GenerateSelfSignedCertificate private static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Signature Algorithm const string signatureAlgorithm = "SHA256WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); // Issuer and Subject Name var subjectDN = new X509Name(subjectName); X509Name issuerDN = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddDays(7); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Subject Public Key AsymmetricCipherKeyPair subjectKeyPair; var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Generating the Certificate var issuerKeyPair = subjectKeyPair; // selfsign certificate var certificate = certificateGenerator.Generate(issuerPrivKey, random); // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; if (algID.ObjectID.Equals(PkcsObjectIdentifiers.RsaEncryption)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( (Asn1Sequence)keyInfo.PrivateKey); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } else if (algID.ObjectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new DHPrivateKeyParameters(derX.Value, new DHParameters(para.P, para.G))); } else if (algID.ObjectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new ElGamalPrivateKeyParameters(derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdDsa)) { DsaParameter para = DsaParameter.GetInstance(algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new DsaPrivateKeyParameters(derX.Value, new DsaParameters(para.P, para.Q, para.G))); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters((Asn1Object)algID.Parameters); ECDomainParameters dParams = null; if (para.IsNamedCurve) { DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; X9ECParameters ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); } } dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } else { X9ECParameters ecP = new X9ECParameters( (Asn1Sequence)para.Parameters); dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } ECPrivateKeyStructure ec = new ECPrivateKeyStructure((Asn1Sequence)keyInfo.PrivateKey); return(new ECPrivateKeyParameters(ec.GetKey(), dParams)); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { throw new NotImplementedException(); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence)algID.Parameters); DerOctetString derX = (DerOctetString)keyInfo.PrivateKey; byte[] keyEnc = derX.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger x = new BigInteger(1, keyBytes); return(new Gost3410PrivateKeyParameters(x, algParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public Pkcs12SafeBagBuilder(PrivateKeyInfo privateKeyInfo) { this.bagType = PkcsObjectIdentifiers.KeyBag; this.bagValue = privateKeyInfo; }
public Pkcs12SafeBagBuilder(IAsymmetricPrivateKey privateKey) : this(PrivateKeyInfo.GetInstance(privateKey.GetEncoded())) { }
public Pkcs12SafeBagBuilder(PrivateKeyInfo privateKeyInfo, ICipherBuilder <AlgorithmIdentifier> encryptor) { this.bagType = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag; this.bagValue = new Pkcs8EncryptedPrivateKeyInfoBuilder(privateKeyInfo).Build(encryptor).ToAsn1Structure(); }
public Pkcs12SafeBagBuilder(IAsymmetricPrivateKey privateKey, ICipherBuilder <AlgorithmIdentifier> encryptor) : this(PrivateKeyInfo.GetInstance(privateKey.GetEncoded()), encryptor) { }
/// <summary> /// Constructor from an algorithm and a PrivateKeyInfo object containing a NewHope private key. /// </summary> /// <param name="algorithm">Algorithm marker to associate with the key.</param> /// <param name="privateKeyInfo">A PrivateKeyInfo object.</param> public AsymmetricNHPrivateKey(Algorithm algorithm, PrivateKeyInfo privateKeyInfo) : base(algorithm) { this.privateKeyData = Convert(Asn1OctetString.GetInstance(privateKeyInfo.ParsePrivateKey()).GetOctets()); }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algOid = algID.Algorithm; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } // TODO? // else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return(new DsaPrivateKeyParameters(derX.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger d = ec.GetKey(); if (para.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPrivateKeyParameters(d, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object privKey = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure ec; if (privKey is DerInteger) { ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue); } else { ec = ECPrivateKeyStructure.GetInstance(privKey); } return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); Asn1Object privKey = keyInfo.ParsePrivateKey(); BigInteger x; if (privKey is DerInteger) { x = DerInteger.GetInstance(privKey).PositiveValue; } else { x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets())); } return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
/// <summary> /// /// </summary> /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks> /// <param name="subjectName"></param> /// <returns></returns> public static void GenerateCertificate(string subjectName, DateTime expireOnUtc, byte[] issuingCertificate, string issuingCertificatePassword, out string password, out byte[] cerData, out byte[] pkcs12Data) { AsymmetricKeyParameter caPrivateKey; var caCert = ReadCertificateFromBytes(issuingCertificate, issuingCertificatePassword, out caPrivateKey); var caAuth = new AuthorityKeyIdentifierStructure(caCert); var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier()); // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; var rnd = new Random(); var result = new string( Enumerable.Repeat(chars, 15) .Select(s => s[rnd.Next(s.Length)]) .ToArray()); password = result; var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); var serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(caCert.IssuerDN); // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes()) gen.SetNotAfter(expireOnUtc); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA"); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); gen.SetPublicKey(subjectKeyPair.Public); //gen.AddExtension( // X509Extensions.ExtendedKeyUsage.Id, // false, // new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning })); //1.3.6.1.5.5.7.3.1 = server authentication //1.3.6.1.5.5.7.3.2 = client authentication //1.3.6.1.5.5.7.3.3 = code signing var certificate = gen.Generate(caPrivateKey); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.ImportParameters(rsaParameters); x509.PrivateKey = rsaKey; cerData = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password); }
public EncKeyWithID(PrivateKeyInfo privKeyInfo) { this.privKeyInfo = privKeyInfo; this.identifier = null; }
public static void GenerateRootCertificate(string subjectName, DateTime expireOnUtc, out string password, out string pemValue, out byte[] cerData, out byte[] pkcs12Data) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); BigInteger serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotAfter(expireOnUtc); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA256WithRSA"); gen.SetPublicKey(subjectKeyPair.Public); var certificate = gen.Generate(subjectKeyPair.Private, random); var privateKeyPem = new StringBuilder(); var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem)); privateKeyPemWriter.WriteObject(certificate); privateKeyPemWriter.WriteObject(subjectKeyPair.Private); privateKeyPemWriter.Writer.Flush(); pemValue = privateKeyPem.ToString(); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.ImportParameters(rsaParameters); x509.PrivateKey = rsaKey; // Generating Random Numbers var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; var rnd = new Random(); var result = new string( Enumerable.Repeat(chars, 15) .Select(s => s[rnd.Next(s.Length)]) .ToArray()); password = result; cerData = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password); }
public EncKeyWithID(PrivateKeyInfo privKeyInfo, GeneralName generalName) { this.privKeyInfo = privKeyInfo; this.identifier = generalName; }
public static AsymmetricKeyParameter CreateKey(byte[] privateKeyInfoData) { return(CreateKey(PrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(privateKeyInfoData)))); }
/// <summary> /// Generates a ca certificate /// </summary> /// <param name="privateKey">The CA private key used to sign certificates</param> /// <param name="base64EncodedCer">The cer file used to configure the browser</param> /// <returns></returns> public static void GenerateCACert(out string privateKey, out string base64EncodedCer) { string subjectName = CA_NAME; int keyStrength = 1024; // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var subjectDN = new X509Name(subjectName); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); // Subject Public Key AsymmetricCipherKeyPair subjectKeyPair; var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Generating the Certificate var issuerKeyPair = subjectKeyPair; ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", issuerKeyPair.Private, random); var certificate = certificateGenerator.Generate(signatureFactory); base64EncodedCer = String.Format("-----BEGIN CERTIFICATE-----\r\n{0}\r\n-----END CERTIFICATE-----", Convert.ToBase64String(certificate.GetEncoded())); //var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); //System.Security.Cryptography.X509Certificates.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(certificate); //X509Certificate2 dotNetCert2 = new X509Certificate2(dotNetCert); // Add CA certificate to Root store //AddCertToStore(dotNetCert2, StoreName.Root, StoreLocation.LocalMachine); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(issuerKeyPair.Private); privateKey = Convert.ToBase64String(info.GetEncoded()); }
public static AsymmetricKeyParameter CreateKey(Stream inStr) { return(CreateKey(PrivateKeyInfo.GetInstance(Asn1Object.FromStream(inStr)))); }
/** * Read a Key Pair */ private object ReadPrivateKey(PemObject pemObject) { // // extract the key // Debug.Assert(Platform.EndsWith(pemObject.Type, "PRIVATE KEY")); string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] keyBytes = pemObject.Content; IDictionary <string, string> fields = new Dictionary <string, string>(); foreach (PemHeader header in pemObject.Headers) { fields[header.Name] = header.Value; } if (fields.ContainsKey("Proc-Type")) { string procType = (string)fields["Proc-Type"]; if (procType == "4,ENCRYPTED") { if (pFinder == null) { throw new PasswordException("No password finder specified, but a password is required"); } char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } string dekInfo = (string)fields["DEK-Info"]; string[] tknz = dekInfo.Split(','); string dekAlgName = tknz[0].Trim(); byte[] iv = Hex.Decode(tknz[1].Trim()); throw new NotImplementedException("Have not pulled in the entire crypto library."); /* * keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv); */ } } try { AsymmetricKeyParameter pubSpec, privSpec; Asn1Sequence seq = Asn1Sequence.GetInstance(keyBytes); switch (type) { case "RSA": { if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); privSpec = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); break; } case "DSA": { if (seq.Count != 6) { throw new PemException("malformed sequence in DSA private key"); } // TODO Create an ASN1 object somewhere for this? //DerInteger v = (DerInteger)seq[0]; DerInteger p = (DerInteger)seq[1]; DerInteger q = (DerInteger)seq[2]; DerInteger g = (DerInteger)seq[3]; DerInteger y = (DerInteger)seq[4]; DerInteger x = (DerInteger)seq[5]; DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value); privSpec = new DsaPrivateKeyParameters(x.Value, parameters); pubSpec = new DsaPublicKeyParameters(y.Value, parameters); break; } #if ENABLE_EC case "EC": { ECPrivateKeyStructure pKey = ECPrivateKeyStructure.GetInstance(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); // TODO Are the keys returned here ECDSA, as Java version forces? privSpec = PrivateKeyFactory.CreateKey(privInfo); DerBitString pubKey = pKey.GetPublicKey(); if (pubKey != null) { SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes()); // TODO Are the keys returned here ECDSA, as Java version forces? pubSpec = PublicKeyFactory.CreateKey(pubInfo); } else { pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey( (ECPrivateKeyParameters)privSpec); } break; } #endif case "ENCRYPTED": { char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } throw new NotImplementedException("decrypting encrypted keys is not currently supported"); //return PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq)); } case "": { return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq))); } default: throw new ArgumentException("Unknown key type: " + type, "type"); } return(new AsymmetricCipherKeyPair(pubSpec, privSpec)); } catch (IOException e) { throw e; } catch (Exception e) { throw new PemException( "problem creating " + type + " private key: " + e.ToString()); } }
public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo) { //IL_02a2: Unknown result type (might be due to invalid IL or missing references) AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algorithm = privateKeyAlgorithm.Algorithm; if (algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption) || algorithm.Equals(X509ObjectIdentifiers.IdEARsa) || algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algorithm.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient)); } if (algorithm.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger = (DerInteger)keyInfo.ParsePrivateKey(); int l = dHParameter.L?.IntValue ?? 0; DHParameters parameters = new DHParameters(dHParameter.P, dHParameter.G, null, l); return(new DHPrivateKeyParameters(derInteger.Value, parameters, algorithm)); } if (algorithm.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (algorithm.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derInteger3 = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable parameters2 = privateKeyAlgorithm.Parameters; DsaParameters parameters3 = null; if (parameters2 != null) { DsaParameter instance2 = DsaParameter.GetInstance(parameters2.ToAsn1Object()); parameters3 = new DsaParameters(instance2.P, instance2.Q, instance2.G); } return(new DsaPrivateKeyParameters(derInteger3.Value, parameters3)); } if (algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters = ((!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters)); ECPrivateKeyStructure instance3 = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger key = instance3.GetKey(); if (x962Parameters.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", key, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters4 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPrivateKeyParameters(key, parameters4)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet); if (byOid == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object asn1Object = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure eCPrivateKeyStructure = ((!(asn1Object is DerInteger)) ? ECPrivateKeyStructure.GetInstance(asn1Object) : new ECPrivateKeyStructure(byOid.N.BitLength, ((DerInteger)asn1Object).Value)); return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerOctetString derOctetString = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derOctetString.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised"); }
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(); }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.ObjectID; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.PrivateKey; Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return(new DsaPrivateKeyParameters(derX.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters ecP; if (para.IsNamedCurve) { ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { ecP = new X9ECParameters((Asn1Sequence)para.Parameters); } ECDomainParameters dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return(new ECPrivateKeyParameters(ec.GetKey(), dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { return(null); } return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString)keyInfo.PrivateKey; byte[] keyEnc = derX.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger x = new BigInteger(1, keyBytes); return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public Pkcs8EncryptedPrivateKeyInfoBuilder(byte[] privateKeyInfo) : this(PrivateKeyInfo.GetInstance(privateKeyInfo)) { }
public void TestCertMangling() { string certString = @"MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0 WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh 3yILeYQzllt/g0rKVRk="; X509Certificate2 c = new X509Certificate2(); c.Import(Convert.FromBase64String(certString)); Assert.AreEqual("[email protected], CN=www.google.com, O=\"Google, Inc\", L=Mountain View, S=California, C=US", c.Issuer); //Assert.AreEqual("CN=Microsoft Corporate Root CA, O=Microsoft Corporation", c.Subject); Assert.AreEqual("X509", c.GetFormat()); Assert.AreEqual("1.2.840.10045.2.1", c.GetKeyAlgorithm()); Assert.AreEqual("06052B81040022", c.GetKeyAlgorithmParametersString()); Assert.AreEqual("ECC", c.PublicKey.Oid.FriendlyName); ECDiffieHellmanPublicKey certKey = CryptoUtils.ImportEccPublicKeyFromCertificate(c); //Console.WriteLine(certKey.ToXmlString()); // https://blogs.msdn.microsoft.com/shawnfa/2007/01/22/elliptic-curve-diffie-hellman/ // http://stackoverflow.com/questions/11266711/using-cngkey-to-generate-rsa-key-pair-in-pem-dkim-compatible-using-c-simi { string input = "eyJhbGciOiJFUzM4NCIsIng1dSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFN25uWnBDZnhtQ3JTd0RkQnY3ZUJYWE10S2hyb3hPcmlFcjNobU1PSkF1dy9acFFYajFLNUdHdEhTNENwRk50dGQxSllBS1lvSnhZZ2F5a3BpZTBFeUF2M3FpSzZ1dElIMnFuT0F0M1ZOclFZWGZJWkpTL1ZSZTNJbDhQZ3U5Q0IifQo.eyJleHAiOjE0NjQ5ODM4NDUsImV4dHJhRGF0YSI6eyJkaXNwbGF5TmFtZSI6Imd1cnVueCIsImlkZW50aXR5IjoiYWY2ZjdjNWUtZmNlYS0zZTQzLWJmM2EtZTAwNWU0MDBlNTc4In0sImlkZW50aXR5UHVibGljS2V5IjoiTUhZd0VBWUhLb1pJemowQ0FRWUZLNEVFQUNJRFlnQUU3bm5acENmeG1DclN3RGRCdjdlQlhYTXRLaHJveE9yaUVyM2htTU9KQXV3L1pwUVhqMUs1R0d0SFM0Q3BGTnR0ZDFKWUFLWW9KeFlnYXlrcGllMEV5QXYzcWlLNnV0SUgycW5PQXQzVk5yUVlYZklaSlMvVlJlM0lsOFBndTlDQiIsIm5iZiI6MTQ2NDk4Mzg0NH0K.4OrvYYbX09iwOkz-7_N_5yEejuATcUogEbe69fB-kr7r6sH_qSu6bxp9L64SEgABb0rU7tyYCLVnaCSQjd9Dvb34WI9EducgOPJ92qHspcpXr7j716LDfhZE31ksMtWQ"; ECDiffieHellmanPublicKey rootKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V"); Console.WriteLine($"Root Public Key:\n{rootKey.ToXmlString()}"); CngKey key = CngKey.Import(rootKey.ToByteArray(), CngKeyBlobFormat.EccPublicBlob); Console.WriteLine("Key family: " + key.AlgorithmGroup); // "identityPublicKey": "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB", var newKey = CryptoUtils.ImportECDsaCngKeyFromString("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB"); string decoded = JWT.Decode(input, newKey); //Assert.AreEqual("", decoded); //ECDsaCng t = new ECDsaCng(); //t.HashAlgorithm = CngAlgorithm.ECDiffieHellmanP384; //t.KeySize = 384; //byte[] test = t.Key.Export(CngKeyBlobFormat.EccPublicBlob); //Assert.AreEqual(test, newKey); //string decoded = JWT.Decode(input, t.Key); } // Private key (in reality this is not necessary since we will generate it) AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(Base64Url.Decode("MB8CAQAwEAYHKoZIzj0CAQYFK4EEACIECDAGAgEBBAEB")); PrivateKeyInfo privKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey); byte[] derKey = privKeyInfo.GetDerEncoded(); CngKey privCngKey = CngKey.Import(derKey, CngKeyBlobFormat.Pkcs8PrivateBlob); Console.WriteLine(privKeyInfo.PrivateKeyAlgorithm.Algorithm); Console.WriteLine(privCngKey.Algorithm.Algorithm); // Public key ECDiffieHellmanPublicKey clientKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs"); // EC key to generate shared secret ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(privCngKey); ecKey.HashAlgorithm = CngAlgorithm.Sha256; ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ecKey.SecretPrepend = new byte[128]; // Server token //ecKey.SecretPrepend = new byte[0]; // Server token Console.WriteLine(ecKey.HashAlgorithm); Console.WriteLine(ecKey.KeyExchangeAlgorithm); byte[] secret = ecKey.DeriveKeyMaterial(clientKey); Console.WriteLine(Package.HexDump(secret)); Console.WriteLine(Package.HexDump(Base64Url.Decode("ZOBpyzki/M8UZv5tiBih048eYOBVPkQE3r5Fl0gmUP4="))); Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod"))); //Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod"))); }
private SimpleTestResult EncodeRecodePrivateKey() { 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 parameters = new ECKeyGenerationParameters(gostParams, new SecureRandom()); ECKeyPairGenerator engine = new ECKeyPairGenerator(); engine.Init(parameters); AsymmetricCipherKeyPair pair = engine.GenerateKeyPair(); ECPrivateKeyParameters generatedKeyParameters = (ECPrivateKeyParameters)pair.Private; ECPrivateKeyParameters keyParameters = generatedKeyParameters; // // Continuously encode/decode the key and check for loss of information. // for (int t = 0; t < 3; t++) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyParameters); keyParameters = (ECPrivateKeyParameters)PrivateKeyFactory.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 (keyParameters.IsPrivate != generatedKeyParameters.IsPrivate) { return(new SimpleTestResult(false, "isPrivate does not match")); } if (!keyParameters.D.Equals(generatedKeyParameters.D)) { return(new SimpleTestResult(false, "D does not match")); } if (!((ECGost3410Parameters)keyParameters.Parameters).Name.Equals( ((ECGost3410Parameters)generatedKeyParameters.Parameters).Name)) { return(new SimpleTestResult(false, "Name 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)); }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool wrongPkcs12Zero = false; if (password != null && bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); unmarkedKeyEntry = null; IList certBags = Platform.CreateArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; byte[] octets = null; if (oid.Equals(PkcsObjectIdentifiers.Data)) { octets = ((Asn1OctetString)ci.Content).GetOctets(); } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { if (password != null) { EncryptedData d = EncryptedData.GetInstance(ci.Content); octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); } } else { // TODO Other data types } if (octets != null) { Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { certBags.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes, password, wrongPkcs12Zero); } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes); } else { // TODO Other bag types } } } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in certBags) { CertBag certBag = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)certBag.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // IDictionary attributes = Platform.CreateHashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]); Asn1Set attrSet = Asn1Set.GetInstance(sq[1]); if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes); chainCerts[certId] = certEntry; if (unmarkedKeyEntry != null) { if (keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); keyCerts[name] = certEntry; keys[name] = unmarkedKeyEntry; } } else { if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); keyCerts[name] = certEntry; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = certEntry; } } } }