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"); } }
public async Task GetActiveSigningKeyPair_GivenRotationAndMasterKeyCert_ReturnsAKeyPairUsableForTokenSigning() { //Arrange var automocker = new AutoMocker(); var masterKey = new byte[256]; object cachedResult = null; automocker .SetupOptions(new AnonymousTokensConfig { KeyRotationEnabled = true, CurveName = "P-256", MasterKeyCertId = "master-key-cert", KeyRotationInterval = TimeSpan.FromDays(3), KeyRotationRollover = TimeSpan.FromDays(4) }); automocker .Setup <IMemoryCache, bool>(x => x.TryGetValue(It.IsAny <string>(), out cachedResult)) .Returns(false); automocker .Setup <IMemoryCache, ICacheEntry>(x => x.CreateEntry(It.IsAny <string>())) .Returns(Mock.Of <ICacheEntry>()); automocker .Setup <IAnonymousTokenMasterKeyLoader, Task <byte[]> >(x => x.LoadMasterKeyBytes()) .ReturnsAsync(masterKey); var target = automocker.CreateInstance <AnonymousTokenKeyStore>(); //Act var result = await target.GetActiveSigningKeyPair(); //Assert var ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1); var initiator = new Initiator(); var init = initiator.Initiate(ecParameters.Curve); var t = init.t; var r = init.r; var P = init.P; var tokenGenerator = new TokenGenerator(); var(Q, c, z) = tokenGenerator.GenerateToken(result.PrivateKey, result.PublicKey, ecParameters, P); var keyDto = result.AsValidationKey().AsKeyDto(); var clientSideEcParameters = CustomNamedCurves.GetByName(keyDto.Crv); // Matches keyDto.Crv == "P-256" var clientSidePublicKeyPoint = clientSideEcParameters.Curve.CreatePoint(new BigInteger(Convert.FromBase64String(keyDto.X)), new BigInteger(Convert.FromBase64String(keyDto.Y))); var W = initiator.RandomiseToken(clientSideEcParameters, clientSidePublicKeyPoint, P, Q, c, z, r); var tokenVerifier = new TokenVerifier(new InMemorySeedStore()); var isVerified = await tokenVerifier.VerifyTokenAsync(result.PrivateKey, ecParameters.Curve, t, W); isVerified.Should().BeTrue(); }
public void TestSumOfTwoMultiplies() { X9ECParameters x9 = CustomNamedCurves.GetByName("secp256r1"); Assert.NotNull(x9); DoTestSumOfTwoMultiplies(x9); }
static internal ECDomainParameters DecodeCurveParameters(AlgorithmIdentifier algId) { if (!algId.Algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey)) { throw new ArgumentException("Unknown algorithm type: " + algId.Algorithm); } X962Parameters parameters = X962Parameters.GetInstance(algId.Parameters); X9ECParameters x9; if (parameters.IsNamedCurve) { DerObjectIdentifier oid = (DerObjectIdentifier)parameters.Parameters; x9 = CustomNamedCurves.GetByOid(oid); if (x9 == null) { x9 = ECNamedCurveTable.GetByOid(oid); } return(new NamedECDomainParameters(oid, x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed())); } else if (!parameters.IsImplicitlyCA) { x9 = X9ECParameters.GetInstance(parameters.Parameters); return(new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed())); } else { return(null); //return new ECImplicitDomainParameters(CryptoServicesRegistrar.<ECDomainParameters>getProperty(CryptoServicesRegistrar.Property.EC_IMPLICITLY_CA)); } }
//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 ECDomainParameters GetParametersForNamedCurve(int namedCurve) { string curveName = GetNameOfNamedCurve(namedCurve); if (curveName == null) { return(null); } // Parameters are lazily created the first time a particular curve is accessed X9ECParameters ecP = CustomNamedCurves.GetByName(curveName); if (ecP == null) { ecP = ECNamedCurveTable.GetByName(curveName); if (ecP == null) { return(null); } } // It's a bit inefficient to do this conversion every time return(new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed())); }
private void rdCsrKeyDsa_CheckedChanged(object sender, EventArgs e) { if (rdCsrKeyEcdsa.Checked) { if (gbKeyBits.Text == "Key Size") { var newItems = CustomNamedCurves.Names .Cast <string>() .Where(x => CustomNamedCurves.GetOid(x) != null) .Select(x => x == "secp256r1" ? $"{x} (recommended)" : x) .ToArray(); var recommended = newItems.Single(x => x.EndsWith("(recommended)")); gbKeyBits.Text = "Curve"; cbCsKeyBits.Items.Clear(); cbCsKeyBits.Items.AddRange(newItems); cbCsKeyBits.SelectedItem = recommended; } } else { if (gbKeyBits.Text != "Key Size") { var newItems = new[] { "1024 bits", "2048 bits (recommended)", "4096 bits" }; gbKeyBits.Text = "Key Size"; cbCsKeyBits.Items.Clear(); cbCsKeyBits.Items.AddRange(newItems); cbCsKeyBits.SelectedItem = newItems[1]; } } }
static async Task Main(string[] args) { // Import parameters for the elliptic curve prime256v1 var ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1); var publicKeyStore = new InMemoryPublicKeyStore(); var publicKey = await publicKeyStore.GetAsync(); _initiator = new Initiator(); // 1. Initiate communication with a masked point P = r*T = r*Hash(t) var init = _initiator.Initiate(ecParameters.Curve); var t = init.t; var r = init.r; var P = init.P; // 2. Generate token Q = k*P and proof (c,z) of correctness var(Q, proofC, proofZ) = await _tokenApiClient.GenerateTokenAsync(ecParameters.Curve, P); // 3. Randomise the token Q, by removing the mask r: W = (1/r)*Q = k*T. Also checks that proof (c,z) is correct. var W = _initiator.RandomiseToken(ecParameters, publicKey.Q, P, Q, proofC, proofZ, r); // 4. Verify that the token (t,W) is correct. var isVerified = await _tokenApiClient.VerifyTokenAsync(t, W); if (isVerified) { Console.WriteLine("Token is valid."); } else { Console.WriteLine("Token is invalid."); Debug.Fail("Token is invalid."); } }
public void TestMultiply() { ArrayList nameList = new ArrayList(); CollectionUtilities.AddRange(nameList, ECNamedCurveTable.Names); CollectionUtilities.AddRange(nameList, CustomNamedCurves.Names); string[] names = (string[])nameList.ToArray(typeof(string)); Array.Sort(names); ISet oids = new HashSet(); foreach (string name in names) { DerObjectIdentifier oid = ECNamedCurveTable.GetOid(name); if (oid == null) { oid = CustomNamedCurves.GetOid(name); } if (oid != null) { if (oids.Contains(oid)) { continue; } oids.Add(oid); } RandMult(name); } }
public static AsymmetricKeyParameter LoadPrivateKey(byte[] data) { X9ECParameters ecP = CustomNamedCurves.GetByName("curve25519"); ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); ECPrivateKeyParameters prvkey = new ECPrivateKeyParameters(new Org.BouncyCastle.Math.BigInteger(data), ecSpec); return(prvkey); }
internal Signature(BigInteger r, BigInteger s) { R = r; S = s; CurveOrder = CustomNamedCurves.GetByOid(SecObjectIdentifiers.SecP256k1).N; HalfOrder = new BigInteger(CurveOrder.ToByteArray()).ShiftRight(1); }
private static AsymmetricKeyParameter LoadPublicKey(byte[] data) { X9ECParameters ecP = CustomNamedCurves.GetByName("curve25519"); ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); ECPublicKeyParameters pubKey = new ECPublicKeyParameters(ecSpec.Curve.DecodePoint(data), ecSpec); return(pubKey); }
static KeyAgreement() { var curve = CustomNamedCurves.GetByName("secp256r1"); domainParms = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); var m = domainParms.Curve.GetType().GetMethod("DecompressPoint", BindingFlags.NonPublic | BindingFlags.Instance); _decompress = (i, b) => (ECPoint)m.Invoke(domainParms.Curve, new object[] { i, b }); }
public static AsymmetricCipherKeyPair GenerateKeyPair(string curveName, string algorithm) { var ecP = CustomNamedCurves.GetByName(curveName); var ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); var generator = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator(algorithm); generator.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); return(generator.GenerateKeyPair()); }
private static ECPoint DecodePublicKey(AnonymousTokenKey key) { var curve = CustomNamedCurves.GetByName(key.Crv); return(curve.Curve.CreatePoint( new BigInteger(Convert.FromBase64String(key.X)), new BigInteger(Convert.FromBase64String(key.Y)) )); }
internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid) { X9ECParameters byOid = CustomNamedCurves.GetByOid(oid); if (byOid == null) { byOid = ECNamedCurveTable.GetByOid(oid); } return(byOid); }
private async Task <AnonymousTokenSigningKeypair> CreateKeyPairForInterval(long keyIntervalNumber) { var masterKeyBytes = await _masterKeyLoader.LoadMasterKeyBytes(); var ecParameters = CustomNamedCurves.GetByName(_config.CurveName); var keyPairGenerator = new RollingKeyPairGenerator(masterKeyBytes, ecParameters); var(privateKey, publicKey) = keyPairGenerator.GenerateKeyPairForInterval(keyIntervalNumber); return(new AnonymousTokenSigningKeypair(keyIntervalNumber.ToString(), _config.CurveName, privateKey, publicKey)); }
private static ECPublicKeyParameters DecodePublicKey(AnonymousTokenKey key) { var curve = CustomNamedCurves.GetByName(key.Crv); var clientSidePublicKeyPoint = curve.Curve.CreatePoint( new BigInteger(Convert.FromBase64String(key.X)), new BigInteger(Convert.FromBase64String(key.Y)) ); return(new ECPublicKeyParameters("ECDSA", clientSidePublicKeyPoint, new ECDomainParameters(curve))); }
public IKey GenerateKey(int?keySize = null) { var generator = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); var generatorParams = new ECKeyGenerationParameters( CustomNamedCurves.GetOid(curveName), new SecureRandom()); generator.Init(generatorParams); var keyPair = generator.GenerateKeyPair(); return(new AsymmetricCipherKey(Algorithm, keyPair)); }
private static ECPoint GetPublicPointFromPrivate(BigInteger privateKeyPoint) { var CURVE_PARAMS = CustomNamedCurves.GetByName("secp256k1"); var CURVE = new ECDomainParameters(CURVE_PARAMS.Curve, CURVE_PARAMS.G, CURVE_PARAMS.N, CURVE_PARAMS.H); if (privateKeyPoint.BitLength > CURVE.N.BitLength) { privateKeyPoint = privateKeyPoint.Mod(CURVE.N); } return(new FixedPointCombMultiplier().Multiply(CURVE.G, privateKeyPoint)); }
private static void AddCurveParameters(TEllipticCurve curve, DerObjectIdentifier id) { if (id == null) { throw new ArgumentNullException(nameof(id)); } var ecP = CustomNamedCurves.GetByOid(id); _CurveParameters.Add(curve, new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed())); }
internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid) { // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) X9ECParameters ecP = CustomNamedCurves.GetByOid(oid); if (ecP == null) { ecP = ECNamedCurveTable.GetByOid(oid); } return(ecP); }
public static IEnumerable <byte> GetDeriveKey(byte[] key1, AsymmetricCipherKeyPair senderKeyPair, string curveName, string algorithm) { var ecP = CustomNamedCurves.GetByName(curveName); var ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); var publicKey = new ECPublicKeyParameters(ecSpec.Curve.DecodePoint(key1), ecSpec); var agreement = AgreementUtilities.GetBasicAgreement(algorithm); agreement.Init(senderKeyPair.Private); var result = agreement.CalculateAgreement(publicKey); return(result.ToByteArrayUnsigned()); }
public void Setup() { // Import parameters for the elliptic curve prime256v1 _ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1); _initiator = new Initiator(); _tokenGenerator = new TokenGenerator(); _tokenVerifier = new TokenVerifier(new InMemorySeedStore()); SetupWithInMemoryKeyStores(); SetupWithGeneratedKeys(); }
public static Bytes CreatePrivateKey() { var keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("EC"); var curveParams = CustomNamedCurves.GetByName("secp256k1"); var curve = new ECDomainParameters(curveParams.Curve, curveParams.G, curveParams.N, curveParams.H); var ecGenParameterSpec = new ECKeyGenerationParameters(curve, _secureRandom); keyPairGenerator.Init(ecGenParameterSpec); var keyPair = keyPairGenerator.GenerateKeyPair(); return(new Bytes(((ECPrivateKeyParameters)keyPair.Private).D)); }
public TokenController( IPrivateKeyStore privateKeyStore, IPublicKeyStore publicKeyStore, ITokenGenerator tokenGenerator, ITokenVerifier tokenVerifier) { _privateKeyStore = privateKeyStore; _publicKeyStore = publicKeyStore; _tokenGenerator = tokenGenerator; _tokenVerifier = tokenVerifier; _ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1); }
/// <summary> /// Initializes a new instance of <see cref="EllipticCurveAlgorithm"/> class. /// </summary> /// <param name="oid">Object Identifier of the curve</param> /// <param name="curveName">Curve name</param> protected EllipticCurveAlgorithm(string oid, string curveName) { if (curveName == null) { throw new ArgumentNullException("curveName"); } if (oid == null) { throw new ArgumentNullException("oid"); } CurveName = curveName; X9ECParameters x9 = CustomNamedCurves.GetByName(oid); if (x9 != null) { _info = new ECKeyParametersExt(x9); } else { DerObjectIdentifier oidDer; try { oidDer = new DerObjectIdentifier(oid); } catch (FormatException) { throw new InvalidOperationException("Unknown curve: '" + oid + "'."); } _info = new ECKeyParametersExt(oidDer); } BitLength = String.Equals(oid, "curve25519", StringComparison.OrdinalIgnoreCase) ? 256 : _info.Parameters.N.BitLength; if (BitLength <= 256) { SignatureAlgorithm = "SHA-256withECDSA"; } else if (BitLength <= 384) { SignatureAlgorithm = "SHA-384withECDSA"; } else { SignatureAlgorithm = "SHA-512withECDSA"; } }
public void InvalidCurve() { var provider = new KeyAlgorithmProvider(); var generator = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); var generatorParams = new ECKeyGenerationParameters( CustomNamedCurves.GetOid("secp160r1"), new SecureRandom()); generator.Init(generatorParams); var keyPair = generator.GenerateKeyPair(); var der = PrivateKeyInfoFactory.CreatePrivateKeyInfo((keyPair.Private)).GetDerEncoded(); Assert.Throws <NotSupportedException>(() => provider.GetKey(der)); }
public void TestAddSubtractMultiplyTwiceEncoding() { foreach (string name in ECNamedCurveTable.Names) { X9ECParameters x9ECParameters = ECNamedCurveTable.GetByName(name); ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9ECParameters); x9ECParameters = CustomNamedCurves.GetByName(name); if (x9ECParameters != null) { ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9ECParameters); } } }
private static X9ECParameters GetCurveParameters(string name) { X9ECParameters byName = CustomNamedCurves.GetByName(name); if (byName == null) { byName = ECNamedCurveTable.GetByName(name); } if (byName == null) { throw new Exception("unknown curve name: " + name); } return(byName); }