public string setRsa() //初始化,生成PKCS1密钥对,将私钥保存在session中用于解密接收到的密码密文,将公钥传到前端用于密码加密 { RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); //添加参数 RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3), new SecureRandom(), 1024, 25); //初始化构造器 keyGenerator.Init(param); //生成密钥对 AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); TextWriter textWriter = new StringWriter(); PemWriter pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keyPair.Private); //获取密钥对的私钥 pemWriter.Writer.Flush(); //清空缓存区,防止脏写 string priKey = textWriter.ToString(); priKey = RsaKeyConvert.PrivateKeyPkcs1ToPkcs8(priKey); Session["Private"] = priKey; //将私钥保存在session中 TextWriter textWriter1 = new StringWriter(); PemWriter pemWriter1 = new PemWriter(textWriter1); pemWriter1.WriteObject(keyPair.Public); //获取密钥对的公钥 pemWriter1.Writer.Flush(); //清空缓存区,防止脏写 string pubKey = textWriter1.ToString(); Session["pub"] = pubKey; //将私钥保存在session中 //将公钥存入cookie方便读取 Response.Cookies["Key"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["Key"].Value = pubKey; Response.Cookies["Key"].Expires = DateTime.Now.AddDays(1); return(pubKey); //将公钥传到前端 }
public key GetKey() { RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3), new SecureRandom(), 1024, 25); keyPairGenerator.Init(param); AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair(); AsymmetricKeyParameter publicKey = keyPair.Public; AsymmetricKeyParameter privateKey = keyPair.Private; SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object(); byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8"); Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object(); byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8"); return(new key() { publicKey = Convert.ToBase64String(publicInfoByte), privateKey = Convert.ToBase64String(privateInfoByte) }); }
public static RSAKEY GenerateRSAKey() { //RSA密钥对的构造器 RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); //RSA密钥构造器的参数 RsaKeyGenerationParameters param = new RsaKeyGenerationParameters( Org.BouncyCastle.Math.BigInteger.ValueOf(0x3), new Org.BouncyCastle.Security.SecureRandom(), 1024, //密钥长度 25); //用参数初始化密钥构造器 keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); //产生密钥对 AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); //获取公钥和密钥 AsymmetricKeyParameter publicKey = keyPair.Public; AsymmetricKeyParameter privateKey = keyPair.Private; SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object(); byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8"); Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object(); byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8"); RSAKEY item = new RSAKEY() { PublicKey = Convert.ToBase64String(publicInfoByte), PrivateKey = Convert.ToBase64String(privateInfoByte) }; return(item); }
public static RSAKey GetRASKey() { //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) { throw new Exception("failed key generation (1024) length test"); } return(new RSAKey() { PublicKey = SavePublicKey(publicKey), PublicKeyObj = publicKey, PrivateKey = SavePrivateKey(privateKey), PrivateKeyObj = privateKey }); }
public static void GenKey(out string publicKey, out string privateKey, out string privateKeyPk8) { publicKey = string.Empty; privateKey = string.Empty; privateKeyPk8 = string.Empty; try { //RSA密钥对的构造器 RsaKeyPairGenerator r = new RsaKeyPairGenerator(); //RSA密钥构造器的参数 RsaKeyGenerationParameters param = new RsaKeyGenerationParameters( Org.BouncyCastle.Math.BigInteger.ValueOf(3), new SecureRandom(), 1024, //密钥长度 25); r.Init(param); AsymmetricCipherKeyPair keyPair = r.GenerateKeyPair(); //获取公钥和密钥 AsymmetricKeyParameter private_key = keyPair.Private; AsymmetricKeyParameter public_key = keyPair.Public; if (((RsaKeyParameters)public_key).Modulus.BitLength < 1024) { Console.WriteLine("failed key generation (1024) length test"); } using (TextWriter textWriter = new StringWriter()) { PemWriter pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keyPair.Private); pemWriter.Writer.Flush(); privateKey = textWriter.ToString(); } using (TextWriter textpubWriter = new StringWriter()) { PemWriter pempubWriter = new PemWriter(textpubWriter); pempubWriter.WriteObject(keyPair.Public); pempubWriter.Writer.Flush(); publicKey = textpubWriter.ToString(); } //keyPair = ReadPem(privateKey); // 直接读取字符串生成密码钥 //public_key = keyPair.Public;//公钥 //private_key = keyPair.Private;//私钥 // 前面私钥为pkcs1格式,经过下面处理后,变成pkcs8格式 SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(public_key); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key); Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object(); byte[] publicInfoByte = asn1ObjectPublic.GetEncoded(); Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object(); byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded(); var pubkeyb64 = Convert.ToBase64String(publicInfoByte); // 这里生成的是Pkcs8的密钥 privateKeyPk8 = PrivateKeyPk8Format(Convert.ToBase64String(privateInfoByte)); privateKey = PrivateKeyFormat(privateKey); publicKey = PublicKeyFormat(publicKey); } catch (Exception ex) { throw ex; } }
public void GenerateCsr(out string publicKey, out string privateKey, out string csr, string name, string pass) { var rsaKeyPairGenerator = new RsaKeyPairGenerator(); var genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 128); rsaKeyPairGenerator.Init(genParam); AsymmetricCipherKeyPair pair = rsaKeyPairGenerator.GenerateKeyPair(); TextWriter textWriter = new StringWriter(); PemWriter pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(pair.Private); pemWriter.Writer.Flush(); privateKey = textWriter.ToString(); DerObjectIdentifier Do = PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc; IDictionary attrs = new Hashtable(); string idhash = new Hash().Create_Hash_For_Identity(name, privateKey); attrs.Add(X509Name.CN, idhash); attrs.Add(X509Name.ST, "SecuNet"); attrs.Add(X509Name.C, "SN"); var subject = new X509Name(new ArrayList(attrs.Keys), attrs); var pkcs10CertificationRequest = new Pkcs10CertificationRequest(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id, subject, pair.Public, null, pair.Private); csr = Convert.ToBase64String(pkcs10CertificationRequest.GetEncoded()); publicKey = pair.Public.ToString(); ihash = idhash; //GeneratePfx(publicKey, privateKey, pass); }
/// <summary> /// Generates certificate request in PKCS#10 format defined by RFC 2986. /// This will also output the private key at the same time. /// ******************************************* /// Notes / Handy references: /// http://www.keylength.com/en/compare/ /// http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57_part1_rev3_general.pdf /// </summary> public void Generate() { try { if (LoadKeyPairFromDisk()) { _logger.Info("Loaded keypair from disk"); } else { var rsaKeyPairGenerator = new RsaKeyPairGenerator(); // Note: the default public exponent in openssl is '65537' var genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(65537), new SecureRandom(), 1024, 5); rsaKeyPairGenerator.Init(genParam); KeyPair = rsaKeyPairGenerator.GenerateKeyPair(); SaveKeyPairToDisk(); } var subject = LoadSubject(); var signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id, KeyPair.Private); _pkcs10CertificationRequest = new Pkcs10CertificationRequest(signatureFactory, subject, KeyPair.Public, null, KeyPair.Private); } catch (Exception ex) { _logger.Error("An error occured during Request Certificate generation", ex); throw new KeyblockException("An error occured during Request Certificate generation", ex); } }
public static CertPrivateKey GenerateRsaPrivateKey(int bits, string PubExp = null) { // Bits less than 1024 are weak Ref: http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html if (bits < RSA_BITS_MINIMUM) { bits = RSA_BITS_DEFAULT; } BigInteger e; if (string.IsNullOrEmpty(PubExp)) { e = RSA_E_F4; } else if (PubExp.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { e = new BigInteger(PubExp, 16); } else { e = new BigInteger(PubExp); } var rsaKgp = new RsaKeyGenerationParameters( e, new SecureRandom(), bits, DEFAULT_CERTAINTY); var rkpg = new RsaKeyPairGenerator(); rkpg.Init(rsaKgp); AsymmetricCipherKeyPair ackp = rkpg.GenerateKeyPair(); return(new CertPrivateKey { KeyPair = ackp, }); }
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(); // // set up the parameters // byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int iterationCount = 100; // // set up the key // char[] password1 = { 'h', 'e', 'l', 'l', 'o' }; EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password1, salt, iterationCount, PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private)); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password1, encInfo); AsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(info); if (!key.Equals(pair.Private)) { Fail("Key corrupted"); } doOpensslTestKeys(); }
public static RSAKey Generate() { try { RSAKey result = new RSAKey(); IAsymmetricCipherKeyPairGenerator gen; KeyGenerationParameters param; gen = new RsaKeyPairGenerator(); param = new RsaKeyGenerationParameters( BigInteger.ValueOf(3L), new SecureRandom(), 2048, 80 ); gen.Init(param); AsymmetricCipherKeyPair pair = gen.GenerateKeyPair(); using (TextWriter textWriter = new StringWriter()) { PemWriter wr = new PemWriter(textWriter); wr.WriteObject(pair.Private); wr.Writer.Flush(); result.PrivatePEM = textWriter.ToString(); } using (TextWriter textWriter = new StringWriter()) { PemWriter wr = new PemWriter(textWriter); wr.WriteObject(pair.Public); wr.Writer.Flush(); result.PublicPEM = textWriter.ToString(); } using (StringReader sr = new StringReader(result.PublicPEM)) { PemReader reader = new PemReader(sr); RsaKeyParameters r = (RsaKeyParameters)reader.ReadObject(); byte[] sshrsa_bytes = Encoding.Default.GetBytes("ssh-rsa"); byte[] n = r.Modulus.ToByteArray(); byte[] e = r.Exponent.ToByteArray(); string buffer64; using (MemoryStream ms = new MemoryStream()){ ms.Write(ToBytes(sshrsa_bytes.Length), 0, 4); ms.Write(sshrsa_bytes, 0, sshrsa_bytes.Length); ms.Write(ToBytes(e.Length), 0, 4); ms.Write(e, 0, e.Length); ms.Write(ToBytes(n.Length), 0, 4); ms.Write(n, 0, n.Length); ms.Flush(); buffer64 = Convert.ToBase64String(ms.ToArray()); } result.PublicSSH = string.Format("ssh-rsa {0} generated-key", buffer64); } return(result); } catch (Org.BouncyCastle.Crypto.CryptoException ex) { throw ex; } }
public static AsymmetricCipherKeyPair RsaKeyPair(this RsaKeyLength size) { RsaKeyPairGenerator gen = new RsaKeyPairGenerator(); RsaKeyGenerationParameters parameters = new RsaKeyGenerationParameters(new BigInteger("10001", 16), SecureRandom.GetInstance("SHA1PRNG"), (int)size, 80); gen.Init(parameters); return(gen.GenerateKeyPair()); }
/// <summary> /// Generate key pair. /// </summary> /// <returns></returns> public override AsymmetricCipherKeyPair GenerateKeyPair() { KeyGenerationParameters parameters = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), Common.ThreadSecureRandom.Value, _keySize, _certainty); IAsymmetricCipherKeyPairGenerator generator = new RsaKeyPairGenerator(); generator.Init(parameters); return(generator.GenerateKeyPair()); }
/// <summary> /// 获取一个密钥对,其中私钥是DES加密后的 /// </summary> /// <param name="userPassword"></param> /// <returns></returns> public static bool CreateRSAKeypair(string pwd, ref KeyPair resultKeypair) { _error = ""; try { resultKeypair = new KeyPair { publicKey = "", privateKey = "" }; //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(); if (((RsaKeyParameters)keyPair.Public).Modulus.BitLength < 1024) { _error = "密钥生成失败,长度不足1024字节。"; return(false); } //获取公钥和密钥 SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object(); byte[] pbkByte = asn1ObjectPublic.GetEncoded(); resultKeypair.publicKey = Convert.ToBase64String(pbkByte); string alg = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1 byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int count = 1000; char[] password = pwd.ToCharArray(); EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( alg, password, salt, count, keyPair.Private); byte[] prkByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded(); resultKeypair.privateKey = Convert.ToBase64String(prkByte); return(true); } catch (Exception ex) { _error = ex.Message; return(false); } }
public virtual void Init(KeyGenerationParameters parameters) { if (parameters is RsaKeyGenerationParameters) { this.parameters = (RsaKeyGenerationParameters)parameters; return; } this.parameters = new RsaKeyGenerationParameters(RsaKeyPairGenerator.DefaultPublicExponent, parameters.Random, parameters.Strength, 100); }
private static AsymmetricCipherKeyPair GenerateKeyPairRsa() { var generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); var generatorParams = new RsaKeyGenerationParameters( new BigInteger("10001", 16), RandomUtil.SecureRandomBc, 2048, 112); generator.Init(generatorParams); return(generator.GenerateKeyPair()); }
public override PrivateKey GeneratePrivateKey(PrivateKeyParams pkp) { var rsaPkParams = pkp as RsaPrivateKeyParams; var ecPkParams = pkp as EcPrivateKeyParams; if (rsaPkParams != null) { int bits; // Bits less than 1024 are weak Ref: http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html if (rsaPkParams.NumBits < RSA_BITS_MINIMUM) { bits = RSA_BITS_DEFAULT; } else { bits = rsaPkParams.NumBits; } BigInteger e; if (string.IsNullOrEmpty(rsaPkParams.PubExp)) { e = RSA_E_F4; } else if (rsaPkParams.PubExp.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { e = new BigInteger(rsaPkParams.PubExp, 16); } else { e = new BigInteger(rsaPkParams.PubExp); } var rsaKgp = new RsaKeyGenerationParameters( e, new SecureRandom(), bits, DEFAULT_CERTAINTY); var rkpg = new RsaKeyPairGenerator(); rkpg.Init(rsaKgp); AsymmetricCipherKeyPair ackp = rkpg.GenerateKeyPair(); return(new RsaPrivateKey(bits, e.ToString(16), ToPrivatePem(ackp))); } else if (ecPkParams != null) { throw new NotImplementedException("EC private keys have not yet been implemented"); //var curveName = Asn1Object.FromShortName("P-256"); ////var curveName = new Asn1Object("P-256"); //using (var ec =OpenSSL.Crypto.EC.Key.FromCurveName(curveName)) //{ // ec.GenerateKey(); //} } else { throw new NotSupportedException("unsupported private key parameter type"); } }
public static AsymmetricCipherKeyPair GenerateKeyPair() { SecureRandom sr = new SecureRandom(); BigInteger pubExp = new BigInteger("10001", 16); RsaKeyGenerationParameters RSAKeyGenPara = new RsaKeyGenerationParameters(pubExp, sr, 1024, 80); RsaKeyPairGenerator RSAKeyPairGen = new RsaKeyPairGenerator(); RSAKeyPairGen.Init(RSAKeyGenPara); return(RSAKeyPairGen.GenerateKeyPair()); }
public CryptoHandler() { RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); KeyGenerationParameters param = new RsaKeyGenerationParameters( Org.BouncyCastle.Math.BigInteger.ValueOf(3), new Org.BouncyCastle.Security.SecureRandom(), 1024, 25); keyGenerator.Init(param); keyPair = keyGenerator.GenerateKeyPair(); }
public static AsymmetricCipherKeyPair GenerateKeys(int Strength) { // Another way to get a random...Unsure about the certaninty parameter var rsaKeyParams = new RsaKeyGenerationParameters(BigInteger.ProbablePrime(512, new Random()), new SecureRandom(), Strength, 25); var keyGen = new RsaKeyPairGenerator(); keyGen.Init(rsaKeyParams); return(keyGen.GenerateKeyPair()); }
internal static AsymmetricCipherKeyPair Create(this SignatureAlgorithm algo) { var generator = new RsaKeyPairGenerator(); var generatorParams = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 128); generator.Init(generatorParams); var keyPair = generator.GenerateKeyPair(); return(keyPair); }
PgpKeyRingGenerator CreateKeyRingGenerator(MailboxAddress mailbox, EncryptionAlgorithm algorithm, long expirationTime, string password, DateTime now, SecureRandom random) { var enabledEncryptionAlgorithms = EnabledEncryptionAlgorithms; var enabledDigestAlgorithms = EnabledDigestAlgorithms; var encryptionAlgorithms = new int[enabledEncryptionAlgorithms.Length]; var digestAlgorithms = new int[enabledDigestAlgorithms.Length]; for (int i = 0; i < enabledEncryptionAlgorithms.Length; i++) { encryptionAlgorithms[i] = (int)enabledEncryptionAlgorithms[i]; } for (int i = 0; i < enabledDigestAlgorithms.Length; i++) { digestAlgorithms[i] = (int)enabledDigestAlgorithms[i]; } var parameters = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), random, 2048, 12); var signingAlgorithm = PublicKeyAlgorithmTag.RsaSign; var keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyPairGenerator.Init(parameters); var signingKeyPair = new PgpKeyPair(signingAlgorithm, keyPairGenerator.GenerateKeyPair(), now); var subpacketGenerator = new PgpSignatureSubpacketGenerator(); subpacketGenerator.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify); subpacketGenerator.SetPreferredSymmetricAlgorithms(false, encryptionAlgorithms); subpacketGenerator.SetPreferredHashAlgorithms(false, digestAlgorithms); if (expirationTime > 0) { subpacketGenerator.SetKeyExpirationTime(false, expirationTime); subpacketGenerator.SetSignatureExpirationTime(false, expirationTime); } subpacketGenerator.SetFeature(false, Org.BouncyCastle.Bcpg.Sig.Features.FEATURE_MODIFICATION_DETECTION); var keyRingGenerator = new PgpKeyRingGenerator( PgpSignature.PositiveCertification, signingKeyPair, mailbox.ToString(false), GetSymmetricKeyAlgorithm(algorithm), CharsetUtils.UTF8.GetBytes(password), true, subpacketGenerator.Generate(), null, random); // Add the (optional) encryption subkey. AddEncryptionKeyPair(keyRingGenerator, parameters, PublicKeyAlgorithmTag.RsaGeneral, now, expirationTime, encryptionAlgorithms, digestAlgorithms); return(keyRingGenerator); }
public static void GenerateRsaPair(int keySize) { RsaKeyPairGenerator rsaGen = new RsaKeyPairGenerator(); RsaKeyGenerationParameters keyPar = new RsaKeyGenerationParameters(Org.BouncyCastle.Math.BigInteger.ValueOf(3), new SecureRandom(), keySize, 80); rsaGen.Init(keyPar); AsymmetricCipherKeyPair keyPair = rsaGen.GenerateKeyPair(); AsymmetricKeyParameter pb = keyPair.Public; AsymmetricKeyParameter pr = keyPair.Private; }
/// <summary> /// /// </summary> /// <param name="forPubKey"></param> /// <param name="forPrivKey"></param> /// <param name="keyStrength">1024, 2048,4096</param> /// <param name="exponent">Typically a fermat number 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617,</param> /// <param name="certaninty">Should be 80 or higher depending on Key strength number (exponent)</param> public static void GenerateKeys(out string forPubKey, out string forPrivKey, int keyStrength, int exponent, int certaninty) { // Create key RsaKeyPairGenerator generator = new RsaKeyPairGenerator(); /* * This value should be a Fermat number. 0x10001 (F4) is current recommended value. 3 (F1) is known to be safe also. * 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617, * * Practically speaking, Windows does not tolerate public exponents which do not fit in a 32-bit unsigned integer. Using e=3 or e=65537 works "everywhere". */ BigInteger exponentBigInt = new BigInteger(exponent.ToString()); var param = new RsaKeyGenerationParameters( exponentBigInt, // new BigInteger("10001", 16) publicExponent new SecureRandom(), // SecureRandom.getInstance("SHA1PRNG"),//prng keyStrength, //strength certaninty); //certainty generator.Init(param); AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair(); // Save to export format SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); byte[] ret = info.GetEncoded(); forPubKey = Convert.ToBase64String(ret); // EncryptedPrivateKeyInfo asdf = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( // DerObjectIdentifier.Ber,,,keyPair.Private); //TextWriter textWriter = new StringWriter(); //PemWriter pemWriter = new PemWriter(textWriter); //pemWriter.WriteObject(keyPair); //pemWriter.Writer.Flush(); //string ret2 = textWriter.ToString(); //// demonstration: how to serialise option 1 //TextReader tr = new StringReader(ret2); //PemReader read = new PemReader(tr); //AsymmetricCipherKeyPair something = (AsymmetricCipherKeyPair)read.ReadObject(); //// demonstration: how to serialise option 2 (don't know how to deserailize) //PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); //byte[] privRet = pKinfo.GetEncoded(); //string forPrivKey2Test = Convert.ToBase64String(privRet); PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); byte[] privRet = pKinfo.GetEncoded(); string forPrivKey2Test = Convert.ToBase64String(privRet); forPrivKey = forPrivKey2Test; }
public IKey GenerateKey() { var generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); var generatorParams = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 128); generator.Init(generatorParams); var keyPair = generator.GenerateKeyPair(); return(new AsymmetricCipherKey(KeyAlgorithm.RS256, keyPair)); }
public virtual void Init(KeyGenerationParameters parameters) { if (parameters is RsaKeyGenerationParameters) { this.parameters = (RsaKeyGenerationParameters)parameters; } else { this.parameters = new RsaKeyGenerationParameters(DefaultPublicExponent, parameters.Random, parameters.Strength, 100); } }
private static AsymmetricCipherKeyPair GeneratorKeyPair() { SecureRandom rnd = new SecureRandom(); RsaKeyGenerationParameters par = new RsaKeyGenerationParameters(BigInteger.ValueOf(65537), rnd, 1024, 10); RsaKeyPairGenerator gen = new RsaKeyPairGenerator(); gen.Init(par); AsymmetricCipherKeyPair keys = gen.GenerateKeyPair(); return(keys); }
public static AsymmetricCipherKeyPair GenerateBouncyKeyPair() { // Construct a new public/private key pair (RSA 2048 bits) IAsymmetricCipherKeyPairGenerator KeyGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters KeyParams = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 25); KeyGen.Init(KeyParams); AsymmetricCipherKeyPair KeyPair = KeyGen.GenerateKeyPair(); return(KeyPair); }
public void Init( KeyGenerationParameters parameters) { if (parameters is RsaKeyGenerationParameters) { param = (RsaKeyGenerationParameters)parameters; } else { param = new RsaKeyGenerationParameters( DefaultPublicExponent, parameters.Random, parameters.Strength, DefaultTests); } }
public static AsymmetricCipherKeyPair GenerateRsaKeyPair( BigInteger publicExponent, SecureRandom random, int strength, int certainty) { RsaKeyPairGenerator generator = new RsaKeyPairGenerator(); RsaKeyGenerationParameters parameters = new RsaKeyGenerationParameters( publicExponent, random, strength, certainty); generator.Init(parameters); return(generator.GenerateKeyPair()); }
internal KeyPairGenerator(KeyGenerationParameters keyGenParameters, SecureRandom random) : base(keyGenParameters) { int keySize = keyGenParameters.KeySize; keyGenParameters.Validate(); if (CryptoServicesRegistrar.IsInApprovedOnlyMode()) { Utils.ValidateKeyPairGenRandom(random, Utils.GetAsymmetricSecurityStrength(keySize), Alg); } this.param = new RsaKeyGenerationParameters(keyGenParameters.PublicExponent, random, keySize, keyGenParameters.Certainty); this.engine.Init(param); }