public virtual BigInteger[] GenerateSignature(byte[] message) { AsymmetricCipherKeyPair pair; if (!this.forSigning) { throw new InvalidOperationException("not initialised for signing"); } BigInteger n = ((ECPrivateKeyParameters)this.key).Parameters.N; int bitLength = n.BitLength; BigInteger integer2 = new BigInteger(1, message); int num2 = integer2.BitLength; ECPrivateKeyParameters key = (ECPrivateKeyParameters)this.key; if (num2 > bitLength) { throw new DataLengthException("input too large for ECNR key."); } BigInteger integer3 = null; BigInteger integer4 = null; do { ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.Init(new ECKeyGenerationParameters(key.Parameters, this.random)); pair = generator.GenerateKeyPair(); ECPublicKeyParameters @public = (ECPublicKeyParameters)pair.Public; integer3 = @public.Q.AffineXCoord.ToBigInteger().Add(integer2).Mod(n); }while (integer3.SignValue == 0); BigInteger d = key.D; integer4 = ((ECPrivateKeyParameters)pair.Private).D.Subtract(integer3.Multiply(d)).Mod(n); return(new BigInteger[] { integer3, integer4 }); }
public override void PerformTest() { StaticTest(); BigInteger n = new BigInteger("6277101735386680763835789423176059013767194773182842284081"); FpCurve curve = new FpCurve( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16), // b n, BigInteger.One); ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G n, BigInteger.One); ECKeyPairGenerator eGen = new ECKeyPairGenerator(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(parameters, new SecureRandom()); eGen.Init(gParam); AsymmetricCipherKeyPair p1 = eGen.GenerateKeyPair(); AsymmetricCipherKeyPair p2 = eGen.GenerateKeyPair(); DoTest(p1, p2); }
public static AsymmetricCipherKeyPair GenerateECKeyPair(SecureRandom random, ECDomainParameters ecParams) { ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(new ECKeyGenerationParameters(ecParams, random)); return(keyPairGenerator.GenerateKeyPair()); }
private string ECC_GY = "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"; //坐标yG public KeyParameter KeyGenerator() { var SM2_ECC_P = new BigInteger(ECC_P, 16); var SM2_ECC_A = new BigInteger(ECC_A, 16); var SM2_ECC_B = new BigInteger(ECC_B, 16); var SM2_ECC_N = new BigInteger(ECC_N, 16); var SM2_ECC_H = BigInteger.One; var SM2_ECC_GX = new BigInteger(ECC_GX, 16); var SM2_ECC_GY = new BigInteger(ECC_GY, 16); ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); var g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); var domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); var keyPairGenerator = new ECKeyPairGenerator(); var aKeyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom()); keyPairGenerator.Init(aKeyGenParams); var aKp = keyPairGenerator.GenerateKeyPair(); var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKp.Public); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKp.Private); var pk = Hex.ToHexString(privateKeyInfo.GetEncoded()); return(new KeyParameter { PrivateKey = Base64.ToBase64String(privateKeyInfo.GetEncoded()), PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded()) }); }
private void ECDH_GenerateEphemeral(EncryptMessage msg) { CBORObject epk = CBORObject.NewMap(); if (_mKey.AsString("kty") == "EC") { X9ECParameters p = NistNamedCurves.GetByName(_mKey.AsString("crv")); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, Message.s_PRNG); pGen.Init(genParam); AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair(); epk.Add("kty", "EC"); epk.Add("crv", _mKey.AsString("crv")); ECPublicKeyParameters priv = (ECPublicKeyParameters)p1.Public; epk.Add("x", priv.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned()); epk.Add("y", priv.Q.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned()); } else if (_mKey.AsString("kty") == "OKP") { switch (_mKey.AsString("crv")) { case "X25519": Ed25519KeyPairGenerator pGen = new Ed25519KeyPairGenerator(); Ed25519KeyGenerationParameters genParam = new Ed25519KeyGenerationParameters(Message.s_PRNG); pGen.Init(genParam); AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair(); Ed25519PublicKeyParameters pub = (Ed25519PublicKeyParameters)p1.Public; epk.Add("kty", "OKP"); epk.Add("crv", "X25519"); epk.Add("x", pub.GetEncoded()); break; default: throw new JoseException("Unknown OPK curve"); } } else { throw new JoseException("Internal Error"); } if (msg.FindAttribute(CBORObject.FromObject("epk"), PROTECTED) != null) { msg.AddAttribute(CBORObject.FromObject("epk"), epk, PROTECTED); } else if (msg.FindAttribute(CBORObject.FromObject("epk"), PROTECTED) != null) { msg.AddAttribute(CBORObject.FromObject("epk"), epk, PROTECTED); } else { AddAttribute("epk", epk, UNPROTECTED); } }
public static CertPrivateKey GenerateEcPrivateKey(int bits) { // From: // http://www.bouncycastle.org/wiki/display/JA1/Elliptic+Curve+Key+Pair+Generation+and+Key+Factories // var csr = new Pkcs10CertificationRequest() // string curveName; // switch (bits) // { // case 256: // curveName = "P-256"; // break; // case 384: // curveName = "P-384"; // break; // default: // throw new ArgumentException("bit length is unsupported or unknown", nameof(bits)); // } // var ecParamSpec = ECNamedCurveTable.GetByName(curveName); // From: // https://www.codeproject.com/Tips/1150485/Csharp-Elliptical-Curve-Cryptography-with-Bouncy-C var ecKpg = new ECKeyPairGenerator("ECDSA"); ecKpg.Init(new KeyGenerationParameters(new SecureRandom(), bits)); var ecKp = ecKpg.GenerateKeyPair(); return(new CertPrivateKey { KeyPair = ecKp }); }
public static PemKeyPair GenerateKeyPair() { String privateKey = String.Empty; String publicKey = String.Empty; X9ECParameters ecParameters = ECNamedCurveTable.GetByName("secp256k1"); ECKeyPairGenerator keyGenerator = new ECKeyPairGenerator(); keyGenerator.Init(new ECKeyGenerationParameters(new ECDomainParameters(ecParameters.Curve, ecParameters.G, ecParameters.N, ecParameters.H), new SecureRandom())); AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); using (TextWriter writer = new StringWriter()) { PemWriter pemWriter = new PemWriter(writer); pemWriter.WriteObject(keyPair.Private); pemWriter.Writer.Flush(); privateKey = writer.ToString(); } using (TextWriter writer = new StringWriter()) { PemWriter pemWriter = new PemWriter(writer); pemWriter.WriteObject(keyPair.Public); pemWriter.Writer.Flush(); publicKey = writer.ToString(); } return(new PemKeyPair(publicKey, privateKey)); }
public static Task <ECDSAKeyPair> Generate() { return(Task.Run(() => { ECKeyGenerationParameters param = new ECKeyGenerationParameters(getDomain(), new Org.BouncyCastle.Security.SecureRandom()); var gen = new ECKeyPairGenerator("EC"); gen.Init(param); var pair = gen.GenerateKeyPair(); var prv = (pair.Private as ECPrivateKeyParameters).D.ToByteArrayUnsigned(); if (prv.Length != 32) { var temp = new byte[32]; Array.Clear(temp, 0, 32 - prv.Length); prv.CopyTo(temp, 32 - prv.Length); prv = temp; Insight.Track("Generate ECDSAKeyPair: prv.Length != 32"); } return new ECDSAKeyPair() { PublicKeyData = (pair.Public as ECPublicKeyParameters).Q.GetEncoded(), PrivateKeyData = prv }; })); }
private void button1_Click(object sender, EventArgs e) { ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(parameters, random); ECKeyPairGenerator keygenerator = new ECKeyPairGenerator("ECGOST3410"); keygenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair pair = keygenerator.GenerateKeyPair(); ECPrivateKeyParameters validatorPrivate = (ECPrivateKeyParameters)pair.Private; ECPublicKeyParameters validatorPublic = (ECPublicKeyParameters)pair.Public; /*validatorPrivate = new ECPrivateKeyParameters( * "ECGOST3410", * new BigInteger("55441196065363246126355624130324183196576709222340016572108097750006097525544"), // d * parameters); * * validatorPublic = new ECPublicKeyParameters( * "ECGOST3410", * new FpPoint(curve, * new FpFieldElement(mod_p, new BigInteger("57520216126176808443631405023338071176630104906313632182896741342206604859403")), // x * new FpFieldElement(mod_p, new BigInteger("17614944419213781543809391949654080031942662045363639260709847859438286763994"))), // y * parameters); */ tbValPrivate.Text = validatorPrivate.D.ToString(16); tbValPublicX.Text = validatorPublic.Q.X.ToBigInteger().ToString(16); tbValPublicY.Text = validatorPublic.Q.Y.ToBigInteger().ToString(16); }
/// <summary> /// get csr /// </summary> /// <param name="issuerName"></param> /// <returns></returns> public static Tuple <string, AsymmetricKeyParameter> GetCsr(string issuerName) { //generate KeyPair var keyGenerator = new ECKeyPairGenerator(); ECKeyGenerationParameters pa = new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, new SecureRandom()); keyGenerator.Init(pa); var keypair = keyGenerator.GenerateKeyPair(); //domain name of CSR file X509Name principal = new X509Name(string.Format("CN={0},OU=client,O=BSN", string.IsNullOrEmpty(issuerName) ? "test02@app0001202004161020152918451" : issuerName)); //load public key SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public); CertificationRequestInfo info = new CertificationRequestInfo(principal, subjectPublicKeyInfo, new DerSet()); //signature byte[] bs = ECDSAHelper.CsrSignData(info.GetEncoded(Asn1Encodable.Der), keypair.Private, pa.DomainParameters.N); //generate csr object Pkcs10CertificationRequest p10 = new Pkcs10CertificationRequest(new CertificationRequest (info, new AlgorithmIdentifier(X9ObjectIdentifiers.ECDsaWithSha256), new DerBitString(bs)).GetEncoded()); //generate csr string Org.BouncyCastle.Utilities.IO.Pem.PemObject pemCSR = new Org.BouncyCastle.Utilities.IO.Pem.PemObject("CERTIFICATE REQUEST", p10.GetEncoded()); StringWriter str = new StringWriter(); Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemCsr = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(str); pemCsr.WriteObject(pemCSR); pemCsr.Writer.Flush(); return(new Tuple <string, AsymmetricKeyParameter>(str.ToString(), keypair.Private)); }
private static AsymmetricCipherKeyPair GenerateKeyPair(ECDomainParameters domainParams, string x) { ECKeyPairGenerator kpg = new ECKeyPairGenerator(); kpg.Init(new ECKeyGenerationParameters(domainParams, new TestRandomBigInteger(x, 16))); return(kpg.GenerateKeyPair()); }
//Method to generate RSA Key Pair #region RSA KeyPair Generation Method public static AsymmetricCipherKeyPair GetKeyPair(string type) { //bouncy Castle librray Method to generate RSA Key Pair if (type == "RSA") { SecureRandom secureRandom = new SecureRandom(); var keyGenerationParameters = new KeyGenerationParameters(secureRandom, RsaKeySize); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); //returning keys AsymmetricCipherKeyPair keypair = keyPairGenerator.GenerateKeyPair(); return(keypair); } else { SecureRandom secureRandom = new SecureRandom(); ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDSA"); //selecting the Secp256k1 curve DerObjectIdentifier oid = SecObjectIdentifiers.SecP256k1; X9ECParameters ecPs = CustomNamedCurves.GetByOid(oid); ECDomainParameters ec = new ECDomainParameters( ecPs.Curve, ecPs.G, ecPs.N, ecPs.H, ecPs.GetSeed()); ECKeyGenerationParameters ecP = new ECKeyGenerationParameters(ec, secureRandom); gen.Init(ecP); return(gen.GenerateKeyPair()); } }
public static X509Certificate2 GenerateSelfSignedCertEcdsa() { var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); const string signatureAlgorithm = "SHA256withECDSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); var subjectDN = new X509Name("CN=simpletorrent"); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); var notBefore = DateTime.UtcNow.Date.AddHours(-24); var notAfter = notBefore.AddYears(1000); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(X962NamedCurves.GetOid("prime256v1"), random); var keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(genParam); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = subjectKeyPair; var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random); var store = new Pkcs12Store(); string friendlyName = certificate.SubjectDN.ToString(); var certificateEntry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); string password = "******"; var stream = new MemoryStream(); store.Save(stream, password.ToCharArray(), random); //mono bug #1660 fix -> convert to definite-length encoding byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray()); var convertedCertificate = new X509Certificate2( pfx, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return(convertedCertificate); }
public SM2CryptoServiceProvider() { ecc_param = sm2_param; ecc_p = new BigInteger(sm2_param[0], 16); ecc_a = new BigInteger(sm2_param[1], 16); ecc_b = new BigInteger(sm2_param[2], 16); ecc_n = new BigInteger(sm2_param[3], 16); ecc_gx = new BigInteger(sm2_param[4], 16); ecc_gy = new BigInteger(sm2_param[5], 16); //ecc_curve = new FpCurve(ecc_p, ecc_a, ecc_b, ecc_gx, ecc_gy); var ecc_gx_fieldelement = new FpFieldElement(ecc_p, ecc_gx); //ecc_curve.FromBigInteger(ecc_gx);// var ecc_gy_fieldelement = new FpFieldElement(ecc_p, ecc_gy); // ecc_curve.FromBigInteger(ecc_gy);// ecc_curve = new FpCurve(ecc_p, ecc_a, ecc_b); // ecc_curve.CreatePoint(ecc_gx, ecc_gy);// ecc_point_g = new FpPoint(ecc_curve, ecc_gx_fieldelement, ecc_gy_fieldelement); ecc_bc_spec = new ECDomainParameters(ecc_curve, ecc_point_g, ecc_n); var ecc_ecgenparam = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom()); ecc_key_pair_generator = new ECKeyPairGenerator(); ecc_key_pair_generator.Init(ecc_ecgenparam); }
// CLIENT TO SERVER STUFF public static AsymmetricCipherKeyPair GenerateClientKey() { var generator = new ECKeyPairGenerator("ECDH"); generator.Init(new ECKeyGenerationParameters(new DerObjectIdentifier("1.3.132.0.34"), SecureRandom.GetInstance("SHA256PRNG"))); return(generator.GenerateKeyPair()); }
internal static AsymmetricCipherKeyPair Create(int pkSize, string pkAlgo) { SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator()); KeyGenerationParameters genParam = new KeyGenerationParameters(random, pkSize); AsymmetricCipherKeyPair keyPair; switch (pkAlgo) { case "RSA": RsaKeyPairGenerator rsaGenerator = new RsaKeyPairGenerator(); rsaGenerator.Init(genParam); keyPair = rsaGenerator.GenerateKeyPair(); break; case "DSA": DsaKeyPairGenerator dsaGenerator = new DsaKeyPairGenerator(); dsaGenerator.Init(genParam); keyPair = dsaGenerator.GenerateKeyPair(); break; case "ECDSA": ECKeyPairGenerator ecGenerator = new ECKeyPairGenerator(pkAlgo); ecGenerator.Init(genParam); keyPair = ecGenerator.GenerateKeyPair(); break; default: throw new ArgumentException("Algorithm not supported", pkAlgo); } return(keyPair); }
public static string[] GenerateKeys(byte[] seed) { ECKeyPairGenerator gen = new ECKeyPairGenerator(); var secureRandom = new SecureRandom(); secureRandom.SetSeed(seed); var keyGenParam = new ECKeyGenerationParameters(domain, secureRandom); gen.Init(keyGenParam); AsymmetricCipherKeyPair keyPair = gen.GenerateKeyPair(); ECPrivateKeyParameters privateParams = (ECPrivateKeyParameters)keyPair.Private; ECPublicKeyParameters publicParams = (ECPublicKeyParameters)keyPair.Public; BigInteger privateKey = privateParams.D; BigInteger publicKey = new BigInteger(publicParams.Q.GetEncoded()); BigInteger publicKeyCompressed = new BigInteger(publicParams.Q.GetEncoded(true)); string[] walletKeyPair = new string[2]; walletKeyPair[0] = privateKey.ToString(16); walletKeyPair[1] = publicKey.ToString(16); return(walletKeyPair); }
public ECKey() { var generator = new ECKeyPairGenerator("EC"); generator.Init(new ECKeyGenerationParameters(CURVE, _secureRandom)); var pair = generator.GenerateKeyPair(); _Key = (ECPrivateKeyParameters)pair.Private; }
private SM2(bool sm2Test) { this.sm2Test = sm2Test; cipher_sm = new Cipher(); //if (sm2Test)//如果为对 // ecc_param = sm2_test_param;//使用国际密码管理局给的测试参数 //else ecc_param = sm2_param; //否则使用国密标准256位曲线参数 ECFieldElement ecc_gx_fieldelement; ECFieldElement ecc_gy_fieldelement; ecc_p = new BigInteger(ecc_param[0], 16); ecc_a = new BigInteger(ecc_param[1], 16); ecc_b = new BigInteger(ecc_param[2], 16); ecc_n = new BigInteger(ecc_param[3], 16); ecc_gx = new BigInteger(ecc_param[4], 16); ecc_gy = new BigInteger(ecc_param[5], 16); ecc_gx_fieldelement = new FpFieldElement(ecc_p, ecc_gx); //选定椭圆曲线上基点G的x坐标 ecc_gy_fieldelement = new FpFieldElement(ecc_p, ecc_gy); //选定椭圆曲线上基点G的坐标 ecc_curve = new FpCurve(ecc_p, ecc_a, ecc_b); //生成椭圆曲线 ecc_point_g = new FpPoint(ecc_curve, ecc_gx_fieldelement, ecc_gy_fieldelement); //生成基点G ecc_bc_spec = new ECDomainParameters(ecc_curve, ecc_point_g, ecc_n); //椭圆曲线,g点坐标,阶n. ECKeyGenerationParameters ecc_ecgenparam; ecc_ecgenparam = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom()); ecc_key_pair_generator = new ECKeyPairGenerator(); ecc_key_pair_generator.Init(ecc_ecgenparam); }
/// <summary> /// Starts key exchange algorithm /// </summary> /// <param name="session">The session.</param> /// <param name="message">Key exchange init message.</param> public override void Start(Session session, KeyExchangeInitMessage message) { base.Start(session, message); Session.RegisterMessage("SSH_MSG_KEX_ECDH_REPLY"); Session.KeyExchangeEcdhReplyMessageReceived += Session_KeyExchangeEcdhReplyMessageReceived; DomainParameters = new ECDomainParameters(CurveParameter.Curve, CurveParameter.G, CurveParameter.N, CurveParameter.H, CurveParameter.GetSeed()); var g = new ECKeyPairGenerator(); g.Init(new ECKeyGenerationParameters(DomainParameters, new SecureRandom())); var aKeyPair = g.GenerateKeyPair(); KeyAgreement = new ECDHCBasicAgreement(); KeyAgreement.Init(aKeyPair.Private); _clientExchangeValue = ((ECPublicKeyParameters)aKeyPair.Public).Q.GetEncoded(); SendMessage(new KeyExchangeEcdhInitMessage(_clientExchangeValue)); }
public static void StartGenerateKeypair(byte[] seed, GenCompleteEventHandler evt) { Thread genThread = new Thread(new ParameterizedThreadStart((o) => { //create a random number generator using SHA512 algorithm SecureRandom rnd = SecureRandom.GetInstance(RANDOM_ALGO); rnd.SetSeed(seed); X9ECParameters curve = TeleTrusTNamedCurves.GetByName(ECDSA_CURVE); ECDomainParameters domain = new ECDomainParameters(curve.Curve, curve.G, curve.N); //create the parameters for initializing the key pair generator using the brainpoolp384t1 curve ECKeyGenerationParameters parms = new ECKeyGenerationParameters(domain, rnd); //create and initialize the key pair generator ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDSA"); gen.Init(parms); //generate the key pair AsymmetricCipherKeyPair kp = gen.GenerateKeyPair(); //trigger the event Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { if (evt != null) { evt(kp); } }); })); genThread.Start(); }
private SM2() { EccParam = CurveParameter; EccP = new BigInteger(EccParam[0], 16); EccA = new BigInteger(EccParam[1], 16); EccB = new BigInteger(EccParam[2], 16); EccN = new BigInteger(EccParam[3], 16); EccGx = new BigInteger(EccParam[4], 16); EccGy = new BigInteger(EccParam[5], 16); ECFieldElement ecc_gx_fieldelement = new FpFieldElement(EccP, EccGx); ECFieldElement ecc_gy_fieldelement = new FpFieldElement(EccP, EccGy); EccCurve = new FpCurve(EccP, EccA, EccB); EccPointG = new FpPoint(EccCurve, ecc_gx_fieldelement, ecc_gy_fieldelement); EccBcSpec = new ECDomainParameters(EccCurve, EccPointG, EccN); ECKeyGenerationParameters ecc_ecgenparam; ecc_ecgenparam = new ECKeyGenerationParameters(EccBcSpec, new SecureRandom()); EccKeyPairGenerator = new ECKeyPairGenerator(); EccKeyPairGenerator.Init(ecc_ecgenparam); }
public void TestECDHBasicAgreementCofactor() { SecureRandom random = new SecureRandom(); X9ECParameters x9 = CustomNamedCurves.GetByName("curve25519"); ECDomainParameters ec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); ECKeyPairGenerator kpg = new ECKeyPairGenerator(); kpg.Init(new ECKeyGenerationParameters(ec, random)); AsymmetricCipherKeyPair p1 = kpg.GenerateKeyPair(); AsymmetricCipherKeyPair p2 = kpg.GenerateKeyPair(); IBasicAgreement e1 = new ECDHBasicAgreement(); IBasicAgreement e2 = new ECDHBasicAgreement(); e1.Init(p1.Private); e2.Init(p2.Private); BigInteger k1 = e1.CalculateAgreement(p2.Public); BigInteger k2 = e2.CalculateAgreement(p1.Public); if (!k1.Equals(k2)) { Fail("calculated agreement test failed"); } }
private static void GenerateIdentity(int keySize = 256) { ECKeyPairGenerator gen = new ECKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(); KeyGenerationParameters keyGenParam = new KeyGenerationParameters(secureRandom, keySize); gen.Init(keyGenParam); var keyPair = gen.GenerateKeyPair(); BigInteger privateKey = ((ECPrivateKeyParameters)keyPair.Private).D; Console.WriteLine("Private key (hex): " + privateKey.ToString(16)); Console.WriteLine("Private key: " + privateKey.ToString(10)); Console.WriteLine("Password for private key encryption:"); var password = Console.ReadLine(); var encryptedPrivateKey = CryptographyUtilities.Encrypt(privateKey.ToByteArray(), password); StorageFileProvider <string> .SetModel(Constants.WalletEncryptedPrivateKeyFilePath, encryptedPrivateKey); ECPoint pubKey = ((ECPublicKeyParameters)keyPair.Public).Q; string pubKeyCompressed = CryptographyUtilities.EncodeECPointHexCompressed(pubKey); Console.WriteLine("Public key (compressed): " + pubKeyCompressed); string addr = CryptographyUtilities.CalcRipeMD160(pubKeyCompressed); Console.WriteLine("Blockchain address: " + addr); }
private static AsymmetricCipherKeyPair GenerateEllipticCurveKeyPair(SecureRandom secureRandom) { var keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, secureRandom)); return(keyPairGenerator.GenerateKeyPair()); }
public void TestECMqvRandom() { var random = new SecureRandom(); var curve = new FPCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b var parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n var pGen = new ECKeyPairGenerator(); pGen.Init(new ECKeyGenerationParameters(parameters, random)); // Pre-established key pairs IAsymmetricCipherKeyPair u1 = pGen.GenerateKeyPair(); IAsymmetricCipherKeyPair v1 = pGen.GenerateKeyPair(); // Ephemeral key pairs IAsymmetricCipherKeyPair u2 = pGen.GenerateKeyPair(); IAsymmetricCipherKeyPair v2 = pGen.GenerateKeyPair(); IBigInteger x = CalculateAgreement(u1, u2, v1, v2); if (x == null) { Fail("MQV Test Vector (random) agreement failed"); } }
private SM2() { ecc_param = sm2_param; ECFieldElement ecc_gx_fieldelement; ECFieldElement ecc_gy_fieldelement; ecc_p = new BigInteger(ecc_param[0], 16); ecc_a = new BigInteger(ecc_param[1], 16); ecc_b = new BigInteger(ecc_param[2], 16); ecc_n = new BigInteger(ecc_param[3], 16); ecc_gx = new BigInteger(ecc_param[4], 16); ecc_gy = new BigInteger(ecc_param[5], 16); ecc_gx_fieldelement = new FpFieldElement(ecc_p, ecc_gx); ecc_gy_fieldelement = new FpFieldElement(ecc_p, ecc_gy); ecc_curve = new FpCurve(ecc_p, ecc_a, ecc_b); ecc_point_g = new FpPoint(ecc_curve, ecc_gx_fieldelement, ecc_gy_fieldelement); ecc_bc_spec = new ECDomainParameters(ecc_curve, ecc_point_g, ecc_n); ECKeyGenerationParameters ecc_ecgenparam; ecc_ecgenparam = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom()); ecc_key_pair_generator = new ECKeyPairGenerator(); ecc_key_pair_generator.Init(ecc_ecgenparam); }
public void TestECDsaP256Sha256WithGeneratedKey() { var secureRandom = new SecureRandom(); X9ECParameters p = NistNamedCurves.GetByName("P-256"); var parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); var ecParams = new ECKeyGenerationParameters(parameters, secureRandom); var ecGen = new ECKeyPairGenerator("ECDSA"); ecGen.Init(ecParams); var pairKey = ecGen.GenerateKeyPair(); var priKey = pairKey.Private as ECPrivateKeyParameters; byte[] m = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); var dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, secureRandom)); IBigInteger[] sig = dsa.GenerateSignature(m); // Verify the signature var pubKey = pairKey.Public as ECPublicKeyParameters; dsa.Init(false, pubKey); if (!dsa.VerifySignature(m, sig[0], sig[1])) { Fail("signature fails"); } }
private byte[] NewKey(int keyLength, object externalPubKey, IDictionary <string, object> header) { // create ECDH-ES content encryption key // generate keypair for ECDH SecureRandom rnd = new SecureRandom(); var keyGen = new ECKeyPairGenerator(); var domainParams = new ECDomainParameters(_brainpoolP256R1.Curve, _brainpoolP256R1.G, _brainpoolP256R1.N, _brainpoolP256R1.H); var genParam = new ECKeyGenerationParameters(domainParams, rnd); keyGen.Init(genParam); var ecdhKeyPair = keyGen.GenerateKeyPair(); var ephemeralPubkey = (ECPublicKeyParameters)ecdhKeyPair.Public; var ephemeralPrvKey = (ECPrivateKeyParameters)ecdhKeyPair.Private; header["epk"] = new Dictionary <string, object> { ["kty"] = "EC", ["x"] = Base64Url.Encode(ephemeralPubkey.Q.XCoord.GetEncoded()), ["y"] = Base64Url.Encode(ephemeralPubkey.Q.YCoord.GetEncoded()), ["crv"] = CRV }; var deriveKey = DeriveKey(header, keyLength, externalPubKey as ECPublicKeyParameters, ephemeralPrvKey); //Console.Out.WriteLine($"dervied key (cek): {VAU.ByteArrayToHexString(deriveKey)}"); return(deriveKey); }
static AsymmetricCipherKeyPair GenerateKeyPair() { Console.WriteLine("Generating signature keys..."); var curve = ECNamedCurveTable.GetByName("secp256k1"); var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed()); var secureRandom = new SecureRandom(); var keyParams = new ECKeyGenerationParameters(domainParams, secureRandom); var generator = new ECKeyPairGenerator("ECDSA"); generator.Init(keyParams); var keyPair = generator.GenerateKeyPair(); var privateKey = keyPair.Private as ECPrivateKeyParameters; var publicKey = keyPair.Public as ECPublicKeyParameters; var strPrivKey = ToHex(privateKey.D.ToByteArrayUnsigned()); var strPubKey = ToHex(publicKey.Q.GetEncoded()); Console.WriteLine($"{strPrivKey.Length} bytes Private key: {strPrivKey}"); Console.WriteLine($"{strPubKey.Length} bytes Public key: {strPubKey}"); Console.WriteLine("Done generating signature keys!"); return(keyPair); }