예제 #1
0
        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();
        }
예제 #2
0
        //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());
            }
        }
예제 #3
0
        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.");
            }
        }
예제 #4
0
        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));
            }
        }
예제 #5
0
        internal Signature(BigInteger r, BigInteger s)
        {
            R = r;
            S = s;

            CurveOrder = CustomNamedCurves.GetByOid(SecObjectIdentifiers.SecP256k1).N;
            HalfOrder  = new BigInteger(CurveOrder.ToByteArray()).ShiftRight(1);
        }
예제 #6
0
    internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid)
    {
        X9ECParameters byOid = CustomNamedCurves.GetByOid(oid);

        if (byOid == null)
        {
            byOid = ECNamedCurveTable.GetByOid(oid);
        }
        return(byOid);
    }
예제 #7
0
        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()));
        }
예제 #8
0
        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);
        }
예제 #9
0
        public TokenController(
            IPrivateKeyStore privateKeyStore,
            IPublicKeyStore publicKeyStore,
            ITokenGenerator tokenGenerator,
            ITokenVerifier tokenVerifier)
        {
            _privateKeyStore = privateKeyStore;
            _publicKeyStore  = publicKeyStore;
            _tokenGenerator  = tokenGenerator;
            _tokenVerifier   = tokenVerifier;

            _ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1);
        }
예제 #10
0
        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();
        }
        /**
         * Retrieve an EC based domain parameter by OID. A custom curve will be returned if one is available.
         *
         * @param paramOid object identifier for the domain parameters.
         * @return the matching domain parameters if found, null otherwise.
         */
        public static NamedECDomainParameters LookupDomainParameters(DerObjectIdentifier paramOid)
        {
            X9ECParameters rv = CustomNamedCurves.GetByOid(paramOid);

            if (rv == null)
            {
                rv = ECNamedCurveTable.GetByOid(paramOid);
            }

            if (rv != null)
            {
                return(new NamedECDomainParameters(paramOid, rv.Curve, rv.G, rv.N, rv.H, rv.GetSeed()));
            }

            return(null);
        }
예제 #12
0
        public ProtocolTests()
        {
            // Import parameters for the elliptic curve prime256v1
            _ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1);

            var publicKeyStore = new InMemoryPublicKeyStore();

            _publicKey = publicKeyStore.GetAsync().GetAwaiter().GetResult();

            var privateKeyStore = new InMemoryPrivateKeyStore();

            _privateKey      = privateKeyStore.GetAsync().GetAwaiter().GetResult();
            _wrongPrivateKey = _privateKey.Add(BigInteger.One);

            _initiator      = new Initiator();
            _tokenGenerator = new TokenGenerator();
            _tokenVerifier  = new TokenVerifier(new InMemorySeedStore());
        }
예제 #13
0
        private void WriteEcPublicKey(ReadOnlySpan <byte> publicKey)
        {
            var ecps = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1) ??
                       ECNamedCurveTable.GetByOid(X9ObjectIdentifiers.Prime256v1);

            byte[] encoded = new byte[publicKey.Length + 1];
            encoded[0] = 0x04;
            publicKey.CopyTo(new Span <byte>(encoded, 1, publicKey.Length));
            var ecdp      = new ECDomainParameters(ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
            var basePoint =
                TlsEccUtilities.ValidateECPublicKey(TlsEccUtilities.DeserializeECPublicKey(null, ecdp, encoded));
            var subinfo         = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(basePoint);
            var publicKeyObject = PublicKeyFactory.CreateKey(subinfo);

            using (var fout = new StreamWriter(File.Open(PublicKey, FileMode.Create))) {
                var writer = new PemWriter(fout);
                writer.WriteObject(publicKeyObject);
            }
        }
예제 #14
0
        // Based on RFCs 5480 and 5915, a named curve is used whenever possible.
        public IEcKey GetPublicKey(byte[] q, string curve)
        {
            ECPublicKeyParameters ecPublicKeyParameter;

            if (curve == "curve25519")
            {
                ecPublicKeyParameter = GetNonStandardCurve(q, curve);
            }
            else
            {
                DerObjectIdentifier curveOid        = ECNamedCurveTable.GetOid(curve) ?? CustomNamedCurves.GetOid(curve);
                X9ECParameters      curveParameters = CustomNamedCurves.GetByOid(curveOid) ?? ECNamedCurveTable.GetByOid(curveOid);

                ECPoint qPoint = curveParameters.Curve.DecodePoint(q);
                ecPublicKeyParameter = new ECPublicKeyParameters("EC", qPoint, curveOid);
            }

            byte[] publicKeyContent = GetPublicKey(ecPublicKeyParameter);
            int    keyLength        = GetKeyLength(ecPublicKeyParameter);
            string curveName        = curveNameMapper.MapCurveToName(ecPublicKeyParameter.Parameters.Curve);

            return(new EcKey(publicKeyContent, AsymmetricKeyType.Public, keyLength, curveName));
        }
예제 #15
0
        private static async Task <ApiResponse> PostSelfExposureKeysWithAnonTokens(SelfDiagnosisSubmissionDTO selfDiagnosisSubmissionDTO, IEnumerable <ExposureKeyModel> temporaryExposureKeys, BaseWebService service)
        {
            var tokenService = new AnonymousTokenService(CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1));
            var token        = await tokenService.GetAnonymousTokenAsync();

            var request = new HttpRequestMessage(HttpMethod.Post, Conf.URL_PUT_UPLOAD_DIAGNOSIS_KEYS);

            request.Headers.Add("Authorization", $"Anonymous {token}");
            string jsonBody = JsonConvert.SerializeObject(selfDiagnosisSubmissionDTO, JsonSerializerSettings);

            request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
            var response = await new HttpClient().SendAsync(request);

            var result = new ApiResponse(Conf.URL_PUT_UPLOAD_DIAGNOSIS_KEYS, HttpMethod.Post);

            result.StatusCode   = (int)response.StatusCode;
            result.ResponseText = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                result.ResponseText = response.ReasonPhrase;
            }
            return(result);
        }
 public TokenVerifierTests()
 {
     _ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1);
 }