Beispiel #1
0
        protected static byte[] ECDH_GenerateSecret(OneKey[] keys)
        {
            if (keys[0][CoseKeyKeys.KeyType].Type != CBORType.Number)
            {
                throw new CoseException("Not an EC Key");
            }
            if (keys[1][CoseKeyKeys.KeyType].Type != CBORType.Number)
            {
                throw new CoseException("Not an EC Key");
            }

            OneKey epkPub  = keys[1];
            OneKey epkPriv = keys[0];

            byte[] temp;

            switch ((GeneralValuesInt)epkPub[CoseKeyKeys.KeyType].AsInt32())
            {
            case GeneralValuesInt.KeyType_OKP:
                if (epkPub[CoseKeyParameterKeys.OKP_Curve].AsInt32() != epkPriv[CoseKeyParameterKeys.OKP_Curve].AsInt32())
                {
                    throw new CoseException("Not a match of curves");
                }

                switch ((GeneralValuesInt)epkPriv[CoseKeyParameterKeys.OKP_Curve].AsInt32())
                {
                case GeneralValuesInt.X25519:
                    temp = X25519.CalculateAgreement(epkPub.AsBytes(CoseKeyParameterKeys.OKP_X), epkPriv.AsBytes(CoseKeyParameterKeys.OKP_D));
                    break;

                default:
                    throw new CoseException("Not a supported Curve");
                }
                return(temp);

            case GeneralValuesInt.KeyType_EC2:

                if (epkPub[CoseKeyParameterKeys.EC_Curve].AsInt32() != epkPriv[CoseKeyParameterKeys.EC_Curve].AsInt32())
                {
                    throw new CoseException("not a match of curves");
                }

                //  Get the curve

                X9ECParameters p        = epkPub.GetCurve();
                ECPoint        pubPoint = epkPub.GetPoint();

                ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);

                ECPublicKeyParameters pub = new ECPublicKeyParameters(pubPoint, parameters);

                ECPrivateKeyParameters priv = new ECPrivateKeyParameters(epkPriv.AsBigInteger(CoseKeyParameterKeys.EC_D), parameters);

                IBasicAgreement e1 = new ECDHBasicAgreement();
                e1.Init(priv);

                BigInteger k1 = e1.CalculateAgreement(pub);


                return(PadBytes(k1.ToByteArrayUnsigned(), p.Curve.FieldSize));

            default:
                throw new CoseException("Not an EC Key");
            }
        }