public void TestNONEwithDSA() { byte[] dummySha1 = Hex.Decode("01020304050607080910111213141516"); SecureRandom rand = new SecureRandom(); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, rand); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters())); IAsymmetricCipherKeyPair kp = g.GenerateKeyPair(); ISigner sig = SignerUtilities.GetSigner("NONEwithDSA"); sig.Init(true, kp.Private); sig.BlockUpdate(dummySha1, 0, dummySha1.Length); byte[] sigBytes = sig.GenerateSignature(); sig.Init(false, kp.Public); sig.BlockUpdate(dummySha1, 0, dummySha1.Length); sig.VerifySignature(sigBytes); // reset test sig.BlockUpdate(dummySha1, 0, dummySha1.Length); if (!sig.VerifySignature(sigBytes)) { Fail("NONEwithDSA failed to reset"); } // lightweight test DsaSigner signer = new DsaSigner(); Asn1Sequence derSig = Asn1Sequence.GetInstance(Asn1Object.FromByteArray(sigBytes)); signer.Init(false, kp.Public); if (!signer.VerifySignature(dummySha1, DerInteger.GetInstance(derSig[0]).Value, DerInteger.GetInstance(derSig[1]).Value)) { Fail("NONEwithDSA not really NONE!"); } }
static void Main(string[] args) { //RSA密鑰產生器 IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); //Key 構造使用參數 kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25)); //1024 key 的長度 AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); char[] password = "******".ToCharArray(); //私鑰的密碼 Stream out1, out2; out1 = File.Create(@"D:\PGP\Sample_priv.asc"); //私鑰放置位置 out2 = File.Create(@"D:\PGP\Sample_pub.asc"); //公鑰放置位置 ExportKeyPair(out1, out2, kp.Public, kp.Private, "INTEL0620", password, true); }
public DiffieHellmanObject CreateBob(DiffieHellmanObject alice) { var bobKeyGen = GeneratorUtilities.GetKeyPairGenerator(Algorithm); var bobParameters = new DHParameters(alice.PrimInteger, alice.NaturalInteger); bobKeyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), bobParameters)); var bobKeyPair = bobKeyGen.GenerateKeyPair(); return(new DiffieHellmanObject { PublicKey = bobKeyPair.Public, PrimInteger = bobParameters.P, NaturalInteger = bobParameters.G, PrivateKey = bobKeyPair.Private }); }
private void GenerateKeyPair() { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECIES"); //TODO ? EcSpec = new ECDomainParameters(X9.Curve, X9.G, X9.N, X9.H); g.Init(new ECKeyGenerationParameters(EcSpec, new SecureRandom())); KeyPair = g.GenerateKeyPair(); if (KeyPair != null) { var q = ((ECPublicKeyParameters)KeyPair.Public).Q.Normalize(); publicKey = X9.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(); } }
/// <summary> /// Generate RSA Key in PKCS1 Format /// </summary> /// <param name="keySize">Key Size - 1024, 2048 or 4096 bytes</param> /// <param name="format">Boolean parameter if you want to format the key</param> /// <returns>List<string></string>Where index 0 is the Private Key and index 1 is the Public Key</returns> public static List <string> Pkcs1Key(int keySize, bool format) { List <string> res = new List <string>(); IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); AsymmetricCipherKeyPair keyPair = kpGen.GenerateKeyPair(); StringWriter sw = new StringWriter(); PemWriter pWrt = new PemWriter(sw); pWrt.WriteObject(keyPair.Private); pWrt.Writer.Close(); string privateKey = sw.ToString(); if (!format) { privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\r\n", ""); } res.Add(privateKey); StringWriter swpub = new StringWriter(); PemWriter pWrtpub = new PemWriter(swpub); pWrtpub.WriteObject(keyPair.Public); pWrtpub.Writer.Close(); string publicKey = swpub.ToString(); if (!format) { publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\r\n", ""); } res.Add(publicKey); return(res); }
/// <summary> /// 生成ECDSA密钥对(secp256k1是比特币椭圆曲线) /// </summary> /// <returns></returns> public static KeyParameter Generator() { var keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256k1, new SecureRandom())); var kp = keyGen.GenerateKeyPair(); var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(kp.Private); return(new KeyParameter { PrivateKey = Base64.ToBase64String(privateKeyInfo.GetEncoded()), PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded()) }); }
/// <inheritdoc /> public async Task <IKey> CreateAsync(string name, string keyType, int size, CancellationToken cancel = default(CancellationToken)) { // Apply defaults. if (string.IsNullOrWhiteSpace(keyType)) { keyType = Options.DefaultKeyType; } if (size < 1) { size = Options.DefaultKeySize; } keyType = keyType.ToLowerInvariant(); // Create the key pair. log.DebugFormat("Creating {0} key named '{1}'", keyType, name); IAsymmetricCipherKeyPairGenerator g; switch (keyType) { case "rsa": g = GeneratorUtilities.GetKeyPairGenerator("RSA"); g.Init(new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), size, 25)); break; case "secp256k1": X9ECParameters ecP = ECNamedCurveTable.GetByName(keyType); if (ecP == null) { throw new Exception("unknown curve name: " + keyType); } var domain = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); g = GeneratorUtilities.GetKeyPairGenerator("EC"); g.Init(new ECKeyGenerationParameters(domain, new SecureRandom())); break; default: throw new Exception($"Invalid key type '{keyType}'."); } var keyPair = g.GenerateKeyPair(); log.Debug("Created key"); return(await AddPrivateKeyAsync(name, keyPair, cancel)); }
private void testNoExtraLocalKeyID(byte[] store1data) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpg.Init(new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25)); AsymmetricCipherKeyPair newPair = kpg.GenerateKeyPair(); Pkcs12Store store1 = new Pkcs12StoreBuilder().Build(); store1.Load(new MemoryStream(store1data, false), passwd); Pkcs12Store store2 = new Pkcs12StoreBuilder().Build(); AsymmetricKeyEntry k1 = store1.GetKey("privatekey"); X509CertificateEntry[] chain1 = store1.GetCertificateChain("privatekey"); X509CertificateEntry[] chain2 = new X509CertificateEntry[chain1.Length + 1]; Array.Copy(chain1, 0, chain2, 1, chain1.Length); chain2[0] = CreateCert(newPair.Public, k1.Key, "*****@*****.**", "*****@*****.**"); if (chain1[0][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { Fail("localKeyID not found initially"); } store2.SetKeyEntry("new", new AsymmetricKeyEntry(newPair.Private), chain2); MemoryStream bOut = new MemoryStream(); store2.Save(bOut, passwd, new SecureRandom()); store2.Load(new MemoryStream(bOut.ToArray(), false), passwd); chain2 = store2.GetCertificateChain("new"); if (chain2[1][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] != null) { Fail("localKeyID found after save"); } }
public void CreateProblemKey() { var keyFound = false; newKey = null; var attempts = 0; while (!keyFound) { var generator = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); var generatorParams = new ECKeyGenerationParameters( CustomNamedCurves.GetOid("P-256"), new SecureRandom() ); generator.Init(generatorParams); var keyPair = generator.GenerateKeyPair(); var publicKey = (ECPublicKeyParameters)keyPair.Public; var xBytes = publicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned(); var yBytes = publicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned(); if (xBytes.Length != yBytes.Length) { System.Diagnostics.Debug.WriteLine($"Problem key found in {attempts} attempts"); keyFound = true; var pem = ""; using (var sr = new StringWriter()) { var pemWriter = new PemWriter(sr); pemWriter.WriteObject(keyPair); pem = sr.ToString(); } System.Diagnostics.Debug.WriteLine($"{pem}"); newKey = KeyFactory.FromPem(pem); } attempts++; } }
public static void GenerateAndTest(string dataToCrypt) { /******* Generating keys **********/ X9ECParameters ecP = CustomNamedCurves.GetByName("curve25519"); ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); IAsymmetricCipherKeyPairGenerator kpgen = GeneratorUtilities.GetKeyPairGenerator("ECDH"); kpgen.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); AsymmetricCipherKeyPair pairA = kpgen.GenerateKeyPair(); AsymmetricCipherKeyPair pairB = kpgen.GenerateKeyPair(); var PrivateA = pairA.Private; var PublicA = pairA.Public; var PrivateB = pairB.Private; var PublicB = pairB.Public; string privateA = new string(BytesToHex(SavePrivateKey(PrivateA))); string publicA = new string(BytesToHex(SavePublicKey(PublicA))); string privateB = new string(BytesToHex(SavePrivateKey(PrivateB))); string publicB = new string(BytesToHex(SavePublicKey(PublicB))); Console.WriteLine("PrvA: " + privateA); Console.WriteLine("PubA: " + publicA); Console.WriteLine("PrvB: " + privateB); Console.WriteLine("PubB: " + publicB); /********* Encrypt and decrypt with signature ***********/ string encrypted = EncryptData(dataToCrypt, privateB, publicA); Console.WriteLine("Encrypted : " + encrypted); string sign = Sign(encrypted, privateB); Console.WriteLine("signature : " + sign); bool isSignedCorrect = IsSignCorrect(encrypted, sign, publicB); Console.WriteLine("Signature is OK ? " + isSignedCorrect); if (isSignedCorrect) { string decrypted = DecryptData(encrypted, privateA, publicB); Console.WriteLine("Is OK " + decrypted.Equals(dataToCrypt)); Console.WriteLine("decrypted Data : " + decrypted); } else { Console.WriteLine("Signature not valid"); } }
/// <summary> /// Generates an RSA key pair for the argument bit length. /// Some typical bit lengths include 1024, 2048 and 4096. /// It is generally agreed upon that modern use of RSA should /// require a minimum of 2048-bit key size. /// </summary> public static PkiKeyPair GenerateRsaKeyPair(int bits, int hashBits = 256) { // Based on: // https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/pkcs/test/PKCS10Test.cs var rsaParams = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), bits, 25); var rsaKpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); rsaKpGen.Init(rsaParams); var nativeKeyPair = rsaKpGen.GenerateKeyPair(); return(new PkiKeyPair(nativeKeyPair, new PkiKeyPairRsaParams(bits) { HashBits = hashBits })); }
/// <summary> /// Generate Pkcs8 format RSA key. Result: Index 0 is the private key and index 1 is the public key /// </summary> /// <param name="keySize">Key Size.Unit: bits</param> /// <param name="format">Whether the format is true If it is standard pem file format</param> /// <returns></returns> public static RSAKey Pkcs8Key(int keySize, bool format) { IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); var keyPair = kpGen.GenerateKeyPair(); StringWriter swpri = new StringWriter(); PemWriter pWrtpri = new PemWriter(swpri); Pkcs8Generator pkcs8 = new Pkcs8Generator(keyPair.Private); pWrtpri.WriteObject(pkcs8); pWrtpri.Writer.Close(); string privateKey = swpri.ToString(); if (!format) { privateKey = privateKey .ReplaceToEmpty(RSAConstants.PRIVATE_KEY_START) .ReplaceToEmpty(RSAConstants.PRIVATE_KEY_END) .ReplaceToEmpty(RSAConstants.R_N); } StringWriter swpub = new StringWriter(); PemWriter pWrtpub = new PemWriter(swpub); pWrtpub.WriteObject(keyPair.Public); pWrtpub.Writer.Close(); string publicKey = swpub.ToString(); if (!format) { publicKey = publicKey .ReplaceToEmpty(RSAConstants.PUBLIC_KEY_START) .ReplaceToEmpty(RSAConstants.PUBLIC_KEY_END) .ReplaceToEmpty(RSAConstants.R_N); } return(new RSAKey { PublicKey = publicKey, PrivateKey = privateKey }); }
/// <summary> /// Creates a random key pair from given curve name /// </summary> /// <param name="curveName"></param> /// <returns></returns> public List <byte[]> CreateRandomKeyPair(string curveName) { var keyPair = new List <byte[]>(); var ecp = TeleTrusTNamedCurves.GetByName(curveName); if (ecp == null) { ecp = NistNamedCurves.GetByName(curveName); } AsymmetricCipherKeyPair kp = null; ECPublicKeyParameters publicKey = null; bool success = false; while (!success) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); var parameters = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed()); var ecP = new ECKeyGenerationParameters(parameters, new SecureRandom()); kpg.Init(ecP); kp = kpg.GenerateKeyPair(); publicKey = (ECPublicKeyParameters)kp.Public; publicKey = SetPublicUncompressed(publicKey); byte[] x = publicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned(); byte[] y = publicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned(); if (x.Length == y.Length) { success = true; } } ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)kp.Private; if (KeysVerified(privateKey, publicKey, curveName)) { var privateBytes = privateKey.D.ToByteArrayUnsigned(); var pubKeyBytes = publicKey.Q.GetEncoded(); keyPair.Add(privateBytes); keyPair.Add(pubKeyBytes); } return(keyPair); }
/// <inheritdoc /> public async Task <IKey> CreateAsync(string name, string keyType, int size, CancellationToken cancel = default(CancellationToken)) { // Apply defaults. if (string.IsNullOrWhiteSpace(keyType)) { keyType = Options.DefaultKeyType; } if (size < 1) { size = Options.DefaultKeySize; } keyType = keyType.ToLowerInvariant(); // Create the key pair. log.DebugFormat("Creating {0} key named '{1}'", keyType, name); IAsymmetricCipherKeyPairGenerator g; switch (keyType) { case "rsa": g = GeneratorUtilities.GetKeyPairGenerator("RSA"); g.Init(new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), size, 25)); break; case "ed25519": g = GeneratorUtilities.GetKeyPairGenerator("Ed25519"); g.Init(new Ed25519KeyGenerationParameters(new SecureRandom())); break; case "secp256k1": g = GeneratorUtilities.GetKeyPairGenerator("EC"); g.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256k1, new SecureRandom())); break; default: throw new Exception($"Invalid key type '{keyType}'."); } var keyPair = g.GenerateKeyPair(); log.Debug("Created key"); return(await AddPrivateKeyAsync(name, keyPair, cancel)); }
private void GenerateElGamal(Stream outSecret, Stream outPublic) { // Prepare a strong Secure Random with seed SecureRandom secureRandom = PgpEncryptionUtil.GetSecureRandom(); IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init((int)PublicKeyLength.BITS_1024, 80, new SecureRandom()); // DSA is 1024 even for long 2048+ ElGamal keys DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(secureRandom, dsaParams); dsaKpg.Init(kgp); // // this takes a while as the key generator has to Generate some DSA parameters // before it Generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); Group elgamalGroup = Precomputed.GetElGamalGroup((int)this.publicKeyLength); if (elgamalGroup == null) { throw new ArgumentException("ElGamal Group not found for key length: " + this.publicKeyLength); } Org.BouncyCastle.Math.BigInteger p = elgamalGroup.GetP(); Org.BouncyCastle.Math.BigInteger g = elgamalGroup.GetG(); secureRandom = PgpEncryptionUtil.GetSecureRandom(); ElGamalParameters elParams = new ElGamalParameters(p, g); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(secureRandom, elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); DsaElGamalKeyGeneratorUtil.ExportKeyPair(outSecret, outPublic, dsaKp, elgKp, identity, passphrase, true); }
public PgpSecretKey GenerateKey() { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "*****@*****.**", SymmetricKeyAlgorithmTag.Cast5, password.ToCharArray(), null, null, new SecureRandom()); return(secretKey); }
public void TestSubgroupConfinement() { DHParameters parameters = Ike2048(); BigInteger p = parameters.P, g = parameters.G; IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH"); //keyGen.initialize(params); keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), parameters)); AsymmetricCipherKeyPair kp = keyGen.GenerateKeyPair(); AsymmetricKeyParameter priv = kp.Private; IBasicAgreement ka = AgreementUtilities.GetBasicAgreement("DH"); BigInteger[] weakPublicKeys = { BigInteger.Zero, BigInteger.One, p.Subtract(BigInteger.One), p, p.Add(BigInteger.One), BigInteger.One.Negate() }; foreach (BigInteger weakKey in weakPublicKeys) { try { new DHPublicKeyParameters(weakKey, parameters); Fail("Generated weak public key"); } catch (ArgumentException ex) { IsTrue("wrong message (constructor)", ex.Message.StartsWith("invalid DH public key")); } ka.Init(priv); try { ka.CalculateAgreement(new DHWeakPubKey(weakKey, parameters)); Fail("Generated secrets with weak public key"); } catch (ArgumentException ex) { IsTrue("wrong message (CalculateAgreement)", "Diffie-Hellman public key is weak".Equals(ex.Message)); } } }
/// <summary> /// Generate Pkcs8 format RSA key. Result: Index 0 is the private key and index 1 is the public key /// </summary> /// <param name="keySize">Key Size.Unit: bits</param> /// <param name="format">Whether the format is true If it is standard pem file format</param> /// <returns></returns> public static List <string> Pkcs8Key(int keySize, bool format = true) { var res = new List <string>(); var kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); var keyPair = kpGen.GenerateKeyPair(); var swpri = new StringWriter(); var pWrtpri = new PemWriter(swpri); var pkcs8 = new Pkcs8Generator(keyPair.Private); pWrtpri.WriteObject(pkcs8); pWrtpri.Writer.Flush(); var privateKey = swpri.ToString(); if (!format) { privateKey = privateKey.Replace("-----BEGIN PRIVATE KEY-----", "") .Replace("-----END PRIVATE KEY-----", "").Replace("\r\n", ""); } res.Add(privateKey); var swpub = new StringWriter(); var pWrtpub = new PemWriter(swpub); pWrtpub.WriteObject(keyPair.Public); pWrtpub.Writer.Flush(); var publicKey = swpub.ToString(); if (!format) { publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "") .Replace("-----END PUBLIC KEY-----", "").Replace("\r\n", ""); } res.Add(publicKey); return(res); }
public static int Main( string[] args) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpg.Init(new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); if (args.Length < 2) { Console.WriteLine("RsaKeyPairGenerator [-a] identity passPhrase"); return(0); } Stream out1, out2; if (args[0].Equals("-a")) { if (args.Length < 3) { Console.WriteLine("RsaKeyPairGenerator [-a] identity passPhrase"); return(0); } out1 = File.Create("secret.asc"); out2 = File.Create("pub.asc"); ExportKeyPair(out1, out2, kp.Public, kp.Private, args[1], args[2].ToCharArray(), true); } else { out1 = File.Create("secret.bpg"); out2 = File.Create("pub.bpg"); ExportKeyPair(out1, out2, kp.Public, kp.Private, args[0], args[1].ToCharArray(), false); } out1.Close(); out2.Close(); return(0); }
/// <summary> /// Create a new ephermal key on the curve. /// </summary> /// <param name="curveName"> /// The name of the curve, for example "P-256". /// </param> /// <returns> /// The new created emphermal key. /// </returns> public static EphermalKey Generate(string curveName) { X9ECParameters ecP = ECNamedCurveTable.GetByName(curveName); if (ecP == null) { throw new Exception($"Unknown curve name '{curveName}'."); } var domain = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); var g = GeneratorUtilities.GetKeyPairGenerator("EC"); g.Init(new ECKeyGenerationParameters(domain, new SecureRandom())); var keyPair = g.GenerateKeyPair(); return(new EphermalKey { privateKey = (ECPrivateKeyParameters)keyPair.Private, publicKey = (ECPublicKeyParameters)keyPair.Public }); }
public DiffieHellmanObject CreateAlice() { var aliceKeyGen = GeneratorUtilities.GetKeyPairGenerator(Algorithm); var aliceGenerator = new DHParametersGenerator(); aliceGenerator.Init(KeyBitSize, DefaultPrimeProbability, new SecureRandom()); var aliceParameters = aliceGenerator.GenerateParameters(); aliceKeyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), aliceParameters)); var aliceKeyPair = aliceKeyGen.GenerateKeyPair(); return(new DiffieHellmanObject { PublicKey = aliceKeyPair.Public, PrimInteger = aliceParameters.P, NaturalInteger = aliceParameters.G, PrivateKey = aliceKeyPair.Private }); }
public override void PerformTest() { IAsymmetricCipherKeyPairGenerator pGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25); pGen.Init(genParam); AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair(); IDictionary attrs = new Hashtable(); attrs.Add(X509Name.C, "AU"); attrs.Add(X509Name.O, "The Legion of the Bouncy Castle"); attrs.Add(X509Name.L, "Melbourne"); attrs.Add(X509Name.ST, "Victoria"); attrs.Add(X509Name.EmailAddress, "*****@*****.**"); X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs); Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest( "SHA1withRSA", subject, pair.Public, null, pair.Private); byte[] bytes = req1.GetEncoded(); Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes); if (!req2.Verify()) { Fail("Failed verify check."); } if (!req2.GetPublicKey().Equals(req1.GetPublicKey())) { Fail("Failed public key check."); } }
/// <summary> /// Generates an RSA key pair for the argument bit length. /// Some typical bit lengths include 1024, 2048 and 4096. /// It is generally agreed upon that modern use of RSA should /// require a minimum of 2048-bit key size. /// </summary> public static PkiKeyPair GenerateRsaKeyPair(int bits, int hashBits = 256) { // Based on: // https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/pkcs/test/PKCS10Test.cs var rsaParams = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), bits, 25); var rsaKpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); rsaKpGen.Init(rsaParams); var nativeKeyPair = rsaKpGen.GenerateKeyPair(); // SHA + ECDSA algor selection based on: // https://github.com/bcgit/bc-csharp/blob/master/crypto/src/security/SignerUtilities.cs var sigAlgor = $"SHA{hashBits}WITHRSA"; return(new PkiKeyPair(nativeKeyPair, PkiAsymmetricAlgorithm.Rsa, (pkey, data) => Sign(sigAlgor, pkey, data), (pkey, data, sig) => Verify(sigAlgor, pkey, data, sig), (keys, prv) => ExportRsJwk(keys, prv))); }
void AddEncryptionKeyPair(PgpKeyRingGenerator keyRingGenerator, KeyGenerationParameters parameters, PublicKeyAlgorithmTag algorithm, DateTime now, long expirationTime, int[] encryptionAlgorithms, int[] digestAlgorithms) { var keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyPairGenerator.Init(parameters); var keyPair = new PgpKeyPair(algorithm, keyPairGenerator.GenerateKeyPair(), now); var subpacketGenerator = new PgpSignatureSubpacketGenerator(); subpacketGenerator.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage); subpacketGenerator.SetPreferredSymmetricAlgorithms(false, encryptionAlgorithms); subpacketGenerator.SetPreferredHashAlgorithms(false, digestAlgorithms); if (expirationTime > 0) { subpacketGenerator.SetKeyExpirationTime(false, expirationTime); subpacketGenerator.SetSignatureExpirationTime(false, expirationTime); } keyRingGenerator.AddSubKey(keyPair, subpacketGenerator.Generate(), null); }
public static RequestSetClientDHParams GetRequest(TServerDHParamsOk serverDhParams, byte[] newNonce, out byte[] clientAgree, out int serverTime) { AesHelper.ComputeAesParameters(newNonce, serverDhParams.ServerNonce, out var aesKeyData); var dhInnerData = DeserializeResponse(serverDhParams, aesKeyData); serverTime = dhInnerData.ServerTime; var p = new BigInteger(1, dhInnerData.DhPrimeAsBinary); var g = BigInteger.ValueOf(dhInnerData.G); var dhParameters = new DHParameters(p, g); KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), dhParameters); var keyGen = GeneratorUtilities.GetKeyPairGenerator("DH"); keyGen.Init(kgp); var clientKeyPair = keyGen.GenerateKeyPair(); var publicKey = ((DHPublicKeyParameters)clientKeyPair.Public); var y = new BigInteger(1, dhInnerData.GAAsBinary); Guard.That(y).IsValidDhPublicKey(dhParameters.P); var serverPublicKey = new DHPublicKeyParameters(y, dhParameters); var clientKeyAgree = AgreementUtilities.GetBasicAgreement("DH"); clientKeyAgree.Init(clientKeyPair.Private); clientAgree = clientKeyAgree.CalculateAgreement(serverPublicKey).ToByteArrayUnsigned(); var clientDhInnerData = new TClientDHInnerData { RetryId = 0, Nonce = serverDhParams.Nonce, ServerNonce = serverDhParams.ServerNonce, GBAsBinary = publicKey.Y.ToByteArray() }; return(SerializeRequest(clientDhInnerData, aesKeyData)); }
public static KeyParameter Pkcs8(int keySize = 2048, bool format = false) { var keyGenerator = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); var keyPair = keyGenerator.GenerateKeyPair(); var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); if (!format) { return(new KeyParameter { PrivateKey = Base64.ToBase64String(privateKeyInfo.GetEncoded()), PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded()) }); } var rsaKey = new KeyParameter(); using (var sw = new StringWriter()) { var pWrt = new PemWriter(sw); var pkcs8 = new Pkcs8Generator(keyPair.Private); pWrt.WriteObject(pkcs8); pWrt.Writer.Close(); rsaKey.PrivateKey = sw.ToString(); } using (var sw = new StringWriter()) { var pWrt = new PemWriter(sw); pWrt.WriteObject(keyPair.Public); pWrt.Writer.Close(); rsaKey.PublicKey = sw.ToString(); } return(rsaKey); }
/// <summary> /// Generate a DSA2 Key pair given its bit size. /// </summary> /// <param name="keySize">"Key bit size of 1024, 2048 or 3072"</param> /// <returns>"DSA2 key pair for the given size"</returns> public AsymmetricCipherKeyPair Dsa2KeyGen(int keySize) { // Check that we got a proper key size int[] allowedKeySizes = { 1024, 2048, 3072 }; if (!(allowedKeySizes.Contains(keySize))) { throw new ArgumentException("KeySize provided is not 1024, 2048 or 3072.", "keySize"); } // Set the proper N parameter depending on the bit key size. int dsa2NParam; if (keySize == 1024) { dsa2NParam = 160; } else { dsa2NParam = 256; } var secRand = new SecureRandom(); var dsa2Genertor = GeneratorUtilities.GetKeyPairGenerator("DSA"); // Generate the proper parameters for the DSA2 Key. var digest = new Sha256Digest(); var paramGen = new DsaParametersGenerator(digest); var dsaParamsList = new DsaParameterGenerationParameters(keySize, dsa2NParam, 80, secRand); paramGen.Init(dsaParamsList); // This will take a while since it has to find a valid random prime number for use. var dsaParams = paramGen.GenerateParameters(); var dsaOptions = new DsaKeyGenerationParameters(secRand, dsaParams); var keyPair = dsa2Genertor.GenerateKeyPair(); return(keyPair); }
public static string GenerateRSAKeyAsPEM(int keySize) { try { IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters generatorParams = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), keySize, 12); generator.Init(generatorParams); AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair(); using (StringWriter sw = new StringWriter()) { PemWriter pemWriter = new PemWriter(sw); pemWriter.WriteObject(keyPair); return(sw.ToString()); } } catch (Exception e) { logger.Error($"Could not generate new key pair: {e.Message}"); return(null); } }
/// <summary> /// 随机生成密钥构造,默认密钥长度1024 /// </summary> public AsymmetricCipher(AsymmetricAlgorithm algorithm, int keySize = 1024) { Algorithm = algorithm ?? throw new NullReferenceException("加密算法不能为空"); var keyGenerator = GeneratorUtilities.GetKeyPairGenerator(algorithm.Generation); var random = new SecureRandom(); if (algorithm == AsymmetricAlgorithm.Dsa) { var dsaParametersGenerator = new DsaParametersGenerator(); dsaParametersGenerator.Init(keySize, 100, random); keyGenerator.Init(new DsaKeyGenerationParameters(random, dsaParametersGenerator.GenerateParameters())); } else { keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); } var keyPair = keyGenerator.GenerateKeyPair(); _publicKeyParameter = keyPair.Public; _privateKeyParameter = keyPair.Private; }
/// <summary> /// DSA密钥对生成 /// </summary> /// <param name="size">size must be from 512 - 1024 and a multiple of 64</param> /// <returns></returns> public static KeyParameter Generator(int size = 1024) { var pGen = new DsaParametersGenerator(); pGen.Init(size, 80, new SecureRandom()); var dsaParams = pGen.GenerateParameters(); var kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); var kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); var kp = kpg.GenerateKeyPair(); var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(kp.Private); return(new KeyParameter { PrivateKey = Base64.ToBase64String(privateKeyInfo.GetEncoded()), PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded()) }); }