public X9ECParameters GetCurve() { CBORObject cborKeyType = m_map[CoseKeyKeys.KeyType]; if (cborKeyType == null) { throw new CoseException("Malformed key struture"); } if ((cborKeyType.Type != CBORType.Number) && !((cborKeyType == GeneralValues.KeyType_EC) || (cborKeyType == GeneralValues.KeyType_OKP))) { throw new CoseException("Not an EC key"); } CBORObject cborCurve = m_map[CoseKeyParameterKeys.EC_Curve]; if (cborCurve.Type == CBORType.Number) { switch ((GeneralValuesInt)cborCurve.AsInt32()) { case GeneralValuesInt.P256: return(NistNamedCurves.GetByName("P-256")); case GeneralValuesInt.P384: return(NistNamedCurves.GetByName("P-384")); case GeneralValuesInt.P521: return(NistNamedCurves.GetByName("P-521")); case GeneralValuesInt.X25519: return(CustomNamedCurves.GetByName("CURVE25519")); default: throw new CoseException("Unsupported key type: " + cborKeyType.AsInt32()); } } else if (cborCurve.Type == CBORType.TextString) { switch (cborCurve.AsString()) { default: throw new CoseException("Unsupported key type: " + cborKeyType.AsString()); } } else { throw new CoseException("Incorrectly encoded key type"); } }
public void TestECDsaP256Sha256() { X9ECParameters p = NistNamedCurves.GetByName("P-256"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d parameters); SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger s = new BigInteger("98506158880355671805367324764306888225238061309262649376965428126566081727535"); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } }
public static bool Verify(byte[] message, byte[] signature, byte[] pubkey, Phantasma.Cryptography.ECC.ECDsaCurve phaCurve = Phantasma.Cryptography.ECC.ECDsaCurve.Secp256r1, SignatureFormat signatureFormat = SignatureFormat.Concatenated) { var signer = SignerUtilities.GetSigner("SHA256withECDSA"); Org.BouncyCastle.Asn1.X9.X9ECParameters curve; switch (phaCurve) { case Phantasma.Cryptography.ECC.ECDsaCurve.Secp256k1: curve = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1"); break; default: curve = NistNamedCurves.GetByName("P-256"); break; } var dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); var point = dom.Curve.DecodePoint(pubkey); var publicKeyParameters = new ECPublicKeyParameters(point, dom); signer.Init(false, publicKeyParameters); signer.BlockUpdate(message, 0, message.Length); switch (signatureFormat) { case SignatureFormat.Concatenated: // We convert from concatenated "raw" R + S format to DER format that Bouncy Castle uses. signature = new Org.BouncyCastle.Asn1.DerSequence( // first 32 bytes is "r" number new Org.BouncyCastle.Asn1.DerInteger(new BigInteger(1, signature.Take(32).ToArray())), // last 32 bytes is "s" number new Org.BouncyCastle.Asn1.DerInteger(new BigInteger(1, signature.Skip(32).ToArray()))) .GetDerEncoded(); break; case SignatureFormat.DEREncoded: // Do nothing, signature already DER-encoded. break; default: throw new Exception("Unknown signature format"); } return(signer.VerifySignature(signature)); }
public void TestECDsaP224OneByteOver() { X9ECParameters p = NistNamedCurves.GetByName("P-224"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d parameters); SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601"))); byte[] M = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79FF"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742"); BigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978"); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("03FD44EC11F9D43D9D23B1E1D1C9ED6519B40ECF0C79F48CF476CC43F1")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } }
public void TestECDsaP521Sha512() { X9ECParameters p = NistNamedCurves.GetByName("P-521"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("617573726813476282316253885608633222275541026607493641741273231656161177732180358888434629562647985511298272498852936680947729040673640492310550142822667389"), // d parameters); SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("6806532878215503520845109818432174847616958675335397773700324097584974639728725689481598054743894544060040710846048585856076812050552869216017728862957612913"))); byte[] M = Hex.Decode("6893B64BD3A9615C39C3E62DDD269C2BAAF1D85915526083183CE14C2E883B48B193607C1ED871852C9DF9C3147B574DC1526C55DE1FE263A676346A20028A66"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("1368926195812127407956140744722257403535864168182534321188553460365652865686040549247096155740756318290773648848859639978618869784291633651685766829574104630"); BigInteger s = new BigInteger("1624754720348883715608122151214003032398685415003935734485445999065609979304811509538477657407457976246218976767156629169821116579317401249024208611945405790"); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("020145E221AB9F71C5FE740D8D2B94939A09E2816E2167A7D058125A06A80C014F553E8D6764B048FB6F2B687CEC72F39738F223D4CE6AFCBFF2E34774AA5D3C342CB3")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } }
/// <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); }
/** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DerObjectIdentifier GetOid(string name) { DerObjectIdentifier oid = X962NamedCurves.GetOid(name); if (oid == null) { oid = SecNamedCurves.GetOid(name); } if (oid == null) { oid = TeleTrusTNamedCurves.GetOid(name); } if (oid == null) { oid = NistNamedCurves.GetOid(name); } return(oid); }
public static byte[] GetSharedSecret(byte[] localPrivateKeyBytes, byte[] remotePublicKeyBytes) { var curve = NistNamedCurves.GetByName("P-256"); var dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, localPrivateKeyBytes), dom); var q = curve.Curve.DecodePoint(new byte[] { 0x04 }.Concat(remotePublicKeyBytes).ToArray()); ECKeyParameters publicKeyParameters = new ECPublicKeyParameters(q, dom); var agreement = new ECDHBasicAgreement(); agreement.Init(privateKeyParameters); using (var sha = SHA256.Create()) { // CalculateAgreement returns a BigInteger, whose length is variable, and bits are not whitened, so hash it. var temp = agreement.CalculateAgreement(publicKeyParameters).ToByteArray(); return(sha.ComputeHash(temp)); } }
// private static ECDomainParameters GetCurveParameters( private static X9ECParameters GetCurveParameters( string name) { X9ECParameters ecP = X962NamedCurves.GetByName(name); if (ecP == null) { ecP = SecNamedCurves.GetByName(name); if (ecP == null) { ecP = NistNamedCurves.GetByName(name); if (ecP == null) { throw new Exception("unknown curve name: " + name); } } } // return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); return(ecP); }
public static BigInteger CalculateSharedKey(BigInteger BIx, BigInteger BIy, ECPrivateKeyParameters privateKey) { IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH"); aKeyAgree.Init(privateKey); X9ECParameters ecP = NistNamedCurves.GetByName("P-521"); ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); FpCurve c = (FpCurve)ecSpec.Curve; ECFieldElement x = new FpFieldElement(c.Q, BIx); ECFieldElement y = new FpFieldElement(c.Q, BIy); ECPoint q = new FpPoint(ecP.Curve, x, y); ECPublicKeyParameters publicKey = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1); BigInteger k1 = aKeyAgree.CalculateAgreement(publicKey); return(k1); }
public ICipherParameters AsPublicKey() { if (PublicKeyX != null) { return(PublicKeyX); } switch (_json["kty"].AsString()) { case "EC": X9ECParameters p = NistNamedCurves.GetByName(this.AsString("crv")); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPoint point = p.Curve.CreatePoint(this.AsBigInteger("x"), this.AsBigInteger("y")); ECPublicKeyParameters pubKey = new ECPublicKeyParameters(point, parameters); PublicKeyX = pubKey; break; } return(PublicKeyX); }
/** * return a X9ECParameters object representing the passed in named * curve. The routine returns null if the curve is not present. * * @param name the name of the curve requested * @return an X9ECParameters object or null if the curve is not available. */ public static X9ECParameters GetByName(string name) { X9ECParameters ecP = X962NamedCurves.GetByName(name); if (ecP == null) { ecP = SecNamedCurves.GetByName(name); } if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByName(name); } if (ecP == null) { ecP = NistNamedCurves.GetByName(name); } return(ecP); }
public static Byte[] getSharedSecret(Byte[] PrivateKeyIn, Byte[] PublicKeyIn) { ECDHCBasicAgreement agreement = new ECDHCBasicAgreement(); X9ECParameters curve = null; ECDomainParameters ecParam = null; ECPrivateKeyParameters privKey = null; ECPublicKeyParameters pubKey = null; ECPoint point = null; curve = NistNamedCurves.GetByName("P-256"); ecParam = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed()); privKey = new ECPrivateKeyParameters(new BigInteger(PrivateKeyIn), ecParam); point = ecParam.Curve.DecodePoint(PublicKeyIn); pubKey = new ECPublicKeyParameters(point, ecParam); agreement.Init(privKey); BigInteger secret = agreement.CalculateAgreement(pubKey); return(secret.ToByteArrayUnsigned()); }
static void ECCTest() { string curveName = "P-521"; var ecP1 = AnssiNamedCurves.GetByName("FRP256v1"); var ecP21 = TeleTrusTNamedCurves.GetByName("brainpoolp512t1"); var ecP = NistNamedCurves.GetByName(curveName); var random = new SecureRandom(); var eCDomainParameters = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); var pGen = new ECKeyPairGenerator(); var genParam = new ECKeyGenerationParameters( eCDomainParameters, random); pGen.Init(genParam); var asymmetricCipherKeyPair = pGen.GenerateKeyPair(); var senderPrivate = ((ECPrivateKeyParameters)asymmetricCipherKeyPair.Private).D.ToByteArray(); var senderPublic = ((ECPublicKeyParameters)asymmetricCipherKeyPair.Public).Q.GetEncoded(); var asymmetricCipherKeyPairA = pGen.GenerateKeyPair(); var recieverPrivate = ((ECPrivateKeyParameters)asymmetricCipherKeyPairA.Private).D.ToByteArray(); var recieverPublic = ((ECPublicKeyParameters)asymmetricCipherKeyPairA.Public).Q.GetEncoded(); var sharedSecret = GetSharedSecretValue(asymmetricCipherKeyPair, asymmetricCipherKeyPairA); var deriveSecret = DeriveSymmetricKeyFromSharedSecret(sharedSecret); var encrypted = Encrypt(Encoding.UTF8.GetBytes(original), deriveSecret); var roundtrip = Encoding.UTF8.GetString(Decrypt(encrypted, deriveSecret)); string hex = Epic.Converters.HexString.Encode(encrypted); string base64 = Convert.ToBase64String(encrypted); Console.WriteLine("Byte: {0}", encrypted.Length); Console.WriteLine("Hex: {0}, {1}", hex.Length, hex); Console.WriteLine("Base64: {0}, {1}", base64.Length, base64); Console.WriteLine("Decode: {0}", roundtrip); }
public void NoncompliantGetByName() { X9ECParameters curve = null; // Elliptic curves always have the key length as part of their names.Rule implementation looks for this //key length pattern, so that all curves with a key length smaller than 224 will raise an issue curve = SecNamedCurves.GetByName("secp192k1"); // Noncompliant {{Use a key length of at least 224 bits for EC cipher algorithm.}} curve = SecNamedCurves.GetByName("secp192r1"); // Noncompliant curve = SecNamedCurves.GetByName("sect163k1"); // Noncompliant curve = SecNamedCurves.GetByName("sect163r1"); // Noncompliant curve = SecNamedCurves.GetByName("sect163r2"); // Noncompliant curve = SecNamedCurves.GetByName("sect193r1"); // Noncompliant curve = SecNamedCurves.GetByName("sect193r2"); // Noncompliant curve = X962NamedCurves.GetByName("prime192v1"); // Noncompliant curve = X962NamedCurves.GetByName("prime192v2"); // Noncompliant curve = X962NamedCurves.GetByName("prime192v3"); // Noncompliant curve = X962NamedCurves.GetByName("c2pnb163v1"); // Noncompliant curve = X962NamedCurves.GetByName("c2pnb163v2"); // Noncompliant curve = X962NamedCurves.GetByName("c2pnb163v3"); // Noncompliant curve = X962NamedCurves.GetByName("c2pnb176w1"); // Noncompliant curve = X962NamedCurves.GetByName("c2tnb191v1"); // Noncompliant curve = X962NamedCurves.GetByName("c2tnb191v2"); // Noncompliant curve = X962NamedCurves.GetByName("c2tnb191v3"); // Noncompliant curve = X962NamedCurves.GetByName("c2pnb208w1"); // Noncompliant curve = TeleTrusTNamedCurves.GetByName("brainpoolp160r1"); // Noncompliant curve = TeleTrusTNamedCurves.GetByName("brainpoolp160t1"); // Noncompliant curve = TeleTrusTNamedCurves.GetByName("brainpoolp192r1"); // Noncompliant curve = TeleTrusTNamedCurves.GetByName("brainpoolp192t1"); // Noncompliant curve = NistNamedCurves.GetByName("B-163"); // Noncompliant curve = NistNamedCurves.GetByName("K-163"); // Noncompliant curve = NistNamedCurves.GetByName("P-192"); // Noncompliant curve = ECNamedCurveTable.GetByName("secp192k1"); // Noncompliant curve = ECNamedCurveTable.GetByName("c2pnb208w1"); // Noncompliant curve = ECNamedCurveTable.GetByName("brainpoolp192t1"); // Noncompliant curve = ECNamedCurveTable.GetByName("B-163"); // Noncompliant }
public static X9ECParameters GetByName(string name) { X9ECParameters byName = X962NamedCurves.GetByName(name); if (byName == null) { byName = SecNamedCurves.GetByName(name); } if (byName == null) { byName = NistNamedCurves.GetByName(name); } if (byName == null) { byName = TeleTrusTNamedCurves.GetByName(name); } if (byName == null) { byName = AnssiNamedCurves.GetByName(name); } return(byName); }
public static byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey) { var signer = SignerUtilities.GetSigner("SHA256withECDSA"); var curve = NistNamedCurves.GetByName("P-256"); var dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, prikey), dom); signer.Init(true, privateKeyParameters); signer.BlockUpdate(message, 0, message.Length); var sig = signer.GenerateSignature(); return(TranscodeSignatureToConcat(sig, 64)); #if OLD_VERSION #if NET461 const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345; prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(prikey).ToArray(); using (CngKey key = CngKey.Import(prikey, CngKeyBlobFormat.EccPrivateBlob)) using (ECDsaCng ecdsa = new ECDsaCng(key)) { return(ecdsa.SignData(message, HashAlgorithmName.SHA256)); } #else using (var ecdsa = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, D = prikey, Q = new ECPoint { X = pubkey.Take(32).ToArray(), Y = pubkey.Skip(32).ToArray() } })) { return(ecdsa.SignData(message, HashAlgorithmName.SHA256)); } #endif #endif }
public static SqlString getSignature(SqlString keySize, SqlString PrivateKey, SqlString Message) { X9ECParameters ecParams = NistNamedCurves.GetByName("P-" + keySize.ToString()); ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed()); var G = ecParams.G; ECCurve curve = ecParams.Curve; //private Key BigInteger d = new BigInteger(PrivateKey.ToString(), 10); ECPrivateKeyParameters keyParameters = new ECPrivateKeyParameters(d, domainParameters); //public key ECPoint q = domainParameters.G.Multiply(d); ECPublicKeyParameters pubkeyParam = new ECPublicKeyParameters(q, domainParameters); string s = Message.ToString(); var signature = BCFunctions.GetSignature(s, keyParameters); var signedString = Convert.ToBase64String(signature); var txtSignature = signedString; return(txtSignature); }
public byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey) { X9ECParameters ecParams = NistNamedCurves.GetByName("P-256"); ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed()); ECPrivateKeyParameters privKeyParam = new ECPrivateKeyParameters( new BigInteger(1, prikey), // d domainParameters); ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA"); signer.Init(true, privKeyParam); signer.BlockUpdate(message, 0, message.Length); //https://crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-asn-1 var signature = signer.GenerateSignature(); var resSignature = new byte[64]; int i = signature[3] == 33 ? 5 : 4; Array.Copy(signature, i, resSignature, 0, 32); i += 32 + 1; i = signature[i] == 33 ? i + 2 : i + 1; Array.Copy(signature, i, resSignature, 32, 32); return resSignature; }
public static string GetName(DerObjectIdentifier oid) { string name = X962NamedCurves.GetName(oid); if (name == null) { name = SecNamedCurves.GetName(oid); } if (name == null) { name = NistNamedCurves.GetName(oid); } if (name == null) { name = TeleTrusTNamedCurves.GetName(oid); } if (name == null) { name = AnssiNamedCurves.GetName(oid); } return(name); }
internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid) { // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) X9ECParameters ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByOid(oid); } } } return(ecP); }
public void Should_GeneratePointOnCurve_When_RandomHashesArePassed() { var curveParams = NistNamedCurves.GetByName("P-256"); var swu = new Swu(((FpCurve)curveParams.Curve).Q, curveParams.Curve.B.ToBigInteger()); var rng = new SecureRandom(); var sha = new Sha512tDigest(256); var random = new byte[32]; for (int i = 0; i <= 10000; i++) { var hash = new byte[32]; rng.NextBytes(random); sha.BlockUpdate(random, 0, random.Length); sha.DoFinal(hash, 0); var(x, y) = swu.HashToPoint(hash); Assert.True(curveParams.Curve.CreatePoint(x, y).IsValid()); sha.Reset(); } }
void OnSvAppSecureHandshake(string id, JsonObj args) { // https://davidtavarez.github.io/2019/implementing-elliptic-curve-diffie-hellman-c-sharp/ X9ECParameters x9Params = NistNamedCurves.GetByName("P-521"); ECDomainParameters domainParams = new ECDomainParameters(x9Params.Curve, x9Params.G, x9Params.N, x9Params.H, x9Params.GetSeed()); ECKeyPairGenerator generator = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator("ECDH"); generator.Init(new ECKeyGenerationParameters(domainParams, new SecureRandom())); AsymmetricCipherKeyPair aliceKeyPair = generator.GenerateKeyPair(); ECPublicKeyParameters alicePublicKeyParams = (ECPublicKeyParameters)aliceKeyPair.Public; string bobKey = args.Get <string>("key"); byte[] bobKeyBytes = System.Convert.FromBase64String(bobKey); var bobPoint = x9Params.Curve.DecodePoint(bobKeyBytes); ECPublicKeyParameters bobPublicKeyParams = new ECPublicKeyParameters("ECDH", bobPoint, SecObjectIdentifiers.SecP521r1); IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH"); agreement.Init(aliceKeyPair.Private); BigInteger sharedSecret = agreement.CalculateAgreement(bobPublicKeyParams); IDigest digest = new Sha256Digest(); byte[] sharedSecretBytes = sharedSecret.ToBytes(66); digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length); derivedKeyBytes = new byte[digest.GetDigestSize()]; digest.DoFinal(derivedKeyBytes, 0); Debug.Log(System.BitConverter.ToString(sharedSecretBytes)); Debug.Log(System.Convert.ToBase64String(derivedKeyBytes)); ReturnSuccess(id, new JsonObj() { ["key"] = alicePublicKeyParams.Q.GetEncoded(), }); }
/// <summary> /// Creates a Signature /// </summary> /// <param name="data"></param> /// <param name="privateKey"></param> /// <param name="curveName"></param> /// <returns></returns> public byte[] CreateSignature(byte[] data, byte[] privateKey, string curveName) { //Get the curve type ec parameters var ecp = TeleTrusTNamedCurves.GetByName(curveName); if (ecp == null) { ecp = NistNamedCurves.GetByName(curveName); } var domainParameters = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed()); var myPriKey = new ECPrivateKeyParameters(new BigInteger(1, privateKey), domainParameters); //Create the signer and initialize with private key var dsa = new ECDsaSigner(); dsa.Init(true, myPriKey); //The signature halves must be equal in length BigInteger[] signature; do { signature = dsa.GenerateSignature(data); }while (signature[0].ToByteArrayUnsigned().Length != signature[1].ToByteArrayUnsigned().Length); //Save both halves in a list var sign = new List <byte>(); foreach (var bigInt in signature) { foreach (var bite in bigInt.ToByteArrayUnsigned()) { sign.Add(bite); } } return(sign.ToArray()); }
public static byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey, Phantasma.Cryptography.ECC.ECDsaCurve phaCurve = Phantasma.Cryptography.ECC.ECDsaCurve.Secp256r1, SignatureFormat signatureFormat = SignatureFormat.Concatenated) { var signer = SignerUtilities.GetSigner("SHA256withECDSA"); Org.BouncyCastle.Asn1.X9.X9ECParameters curve; switch (phaCurve) { case Phantasma.Cryptography.ECC.ECDsaCurve.Secp256k1: curve = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1"); break; default: curve = NistNamedCurves.GetByName("P-256"); break; } var dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, prikey), dom); signer.Init(true, privateKeyParameters); signer.BlockUpdate(message, 0, message.Length); var sig = signer.GenerateSignature(); switch (signatureFormat) { case SignatureFormat.Concatenated: // We convert from default DER format that Bouncy Castle uses to concatenated "raw" R + S format. return(TranscodeSignatureToConcat(sig, 64)); case SignatureFormat.DEREncoded: // Return DER-encoded signature unchanged. return(sig); default: throw new Exception("Unknown signature format"); } }
public byte[] Decrypt(byte[] buffer, byte[] senderPublicKeyBytes, byte[] salt) { var ecP = NistNamedCurves.GetByName("P-256"); ECDomainParameters eCDomainParameters = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N); ECPoint pt = ecP.Curve.DecodePoint(senderPublicKeyBytes); ECPublicKeyParameters senderPublicKey = new ECPublicKeyParameters(pt, eCDomainParameters); var(key, nonce) = DeriveKeyAndNonce(salt, AuthSecret, senderPublicKey, publicKey, privateKey); byte[] result = new byte[0]; var start = 0; // TODO: this is not tested with more than one iteration for (uint i = 0; start < buffer.Length; ++i) { var end = start + CHUNK_SIZE; if (end == buffer.Length) { throw new InvalidOperationException("Truncated payload"); } end = Math.Min(end, buffer.Length); if (end - start <= TAG_LENGTH) { throw new InvalidOperationException("Invalid block: too small at " + i); } byte[] block = DecryptRecord(key, nonce, i, ByteArray.Slice(buffer, start, end), end >= buffer.Length); result = ByteArray.Concat(result, block); start = end; } return(result); }
public static byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey, Phantasma.Cryptography.ECC.ECDsaCurve phaCurve = Phantasma.Cryptography.ECC.ECDsaCurve.Secp256r1) { var signer = SignerUtilities.GetSigner("SHA256withECDSA"); Org.BouncyCastle.Asn1.X9.X9ECParameters curve; switch (phaCurve) { case Phantasma.Cryptography.ECC.ECDsaCurve.Secp256k1: curve = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1"); break; default: curve = NistNamedCurves.GetByName("P-256"); break; } var dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, prikey), dom); signer.Init(true, privateKeyParameters); signer.BlockUpdate(message, 0, message.Length); var sig = signer.GenerateSignature(); return(TranscodeSignatureToConcat(sig, 64)); }
/// <summary> /// Verifies the signature /// </summary> /// <param name="data"></param> /// <param name="signature"></param> /// <param name="publicKey"></param> /// <param name="curveName"></param> /// <returns></returns> public bool VerifiySignature(byte[] data, byte[] signature, byte[] publicKey, string curveName) { //Get curve type ec parameters var ecp = TeleTrusTNamedCurves.GetByName(curveName); if (ecp == null) { ecp = NistNamedCurves.GetByName(curveName); } var domainParameters = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed()); var publicKeyParam = CreatePublicKeyParam(domainParameters, publicKey); //Create the signer and initialize with public key var dsa = new ECDsaSigner(); dsa.Init(false, publicKeyParam); var r = new BigInteger(1, signature.Take(signature.Length / 2).ToArray()); var s = new BigInteger(1, signature.Skip(signature.Length / 2).ToArray()); var verified = dsa.VerifySignature(data, r, s); return(verified); }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo 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)) { RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance( keyInfo.GetPublicKey()); return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent)); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement) || algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPublicKeyParameters(derY.Value, dhParams)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); return(new ElGamalPublicKeyParameters( derY.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); 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 DsaPublicKeyParameters(derY.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters( algID.Parameters.ToAsn1Object()); X9ECParameters ecP; if (para.IsNamedCurve) { // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByOid(oid); } } } } else { ecP = new X9ECParameters((Asn1Sequence)para.Parameters); } ECDomainParameters dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); DerBitString bits = keyInfo.PublicKeyData; byte[] data = bits.GetBytes(); Asn1OctetString key = new DerOctetString(data); X9ECPoint derQ = new X9ECPoint(dParams.Curve, key); return(new ECPublicKeyParameters(derQ.Point, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence)algID.Parameters); Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = key.GetOctets(); byte[] x = new byte[32]; byte[] y = new byte[32]; for (int i = 0; i != y.Length; i++) { x[i] = keyEnc[32 - 1 - i]; } for (int i = 0; i != x.Length; i++) { y[i] = keyEnc[64 - 1 - i]; } ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { return(null); } ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y), false); return(new ECPublicKeyParameters(q, gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence)algID.Parameters); DerOctetString derY; try { derY = (DerOctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = derY.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 y = new BigInteger(1, keyBytes); return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid); } }
public void GetRpkKey(RawPublicKey rpk) { AsymmetricKeyParameter key; try { key = PublicKeyFactory.CreateKey(rpk.SubjectPublicKeyInfo()); } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e); } if (key is ECPublicKeyParameters) { ECPublicKeyParameters ecKey = (ECPublicKeyParameters)key; string s = ecKey.AlgorithmName; OneKey newKey = new OneKey(); newKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_EC); if (ecKey.Parameters.Curve.Equals(NistNamedCurves.GetByName("P-256").Curve)) { newKey.Add(CoseKeyParameterKeys.EC_Curve, GeneralValues.P256); } newKey.Add(CoseKeyParameterKeys.EC_X, CBORObject.FromObject(ecKey.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned())); newKey.Add(CoseKeyParameterKeys.EC_Y, CBORObject.FromObject(ecKey.Q.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned())); if (_serverKeys != null) { foreach (OneKey k in _serverKeys) { if (k.Compare(newKey)) { AuthenticationKey = k; return; } } } TlsEvent ev = new TlsEvent(TlsEvent.EventCode.ServerCertificate) { KeyValue = newKey }; EventHandler <TlsEvent> handler = TlsEventHandler; if (handler != null) { handler(this, ev); } if (!ev.Processed) { // throw new TlsFatalAlert(AlertDescription.certificate_unknown); } AuthenticationKey = ev.KeyValue; } else { // throw new TlsFatalAlert(AlertDescription.certificate_unknown); } }