示例#1
0
文件: MDer.cs 项目: modulexcite/DDer
    static AsnElt BuildInteger(string iv)
    {
        /*
         * If the string can be parsed as a 64-bit integer (signed
         * or unsigned) then we can encoded it right away.
         */
        long v;

        if (Int64.TryParse(iv, out v))
        {
            return(AsnElt.MakeInteger(v));
        }
        ulong uv;

        if (UInt64.TryParse(iv, out uv))
        {
            return(AsnElt.MakeInteger(uv));
        }

        /*
         * For longer values we need ZInt.
         */
        try {
            ZInt z = ZInt.Parse(iv);
            return(AsnElt.MakePrimitive(
                       AsnElt.INTEGER, z.ToBytesBE()));
        } catch {
            throw new IOException(
                      "could not convert value to integer: " + iv);
        }
    }
示例#2
0
 ZInt RunInner(ZInt a, ZInt r, byte[] data, int off, int len)
 {
     byte[] tmp = new byte[16];
     while (len > 0)
     {
         if (len >= 16)
         {
             Array.Copy(data, off, tmp, 0, 16);
         }
         else
         {
             Array.Copy(data, off, tmp, 0, len);
             for (int i = len; i < 16; i++)
             {
                 tmp[i] = 0;
             }
         }
         ByteSwap(tmp, 0, 16);
         ZInt v = ZInt.DecodeUnsignedBE(tmp) | ((ZInt)1 << 128);
         a    = ((a + v) * r) % p;
         off += 16;
         len -= 16;
     }
     return(a);
 }
示例#3
0
        private ZValue ReadZValueFromBsonDocument(BsonReader bsonReader)
        {
            // { "_t" : "ZString", "value" : "" }
            bsonReader.ReadStartDocument();
            BsonType type = bsonReader.ReadBsonType();

            if (type != BsonType.String)
            {
                throw new PBException("error reading ZValue can't find ZValue type \"_t\"");
            }
            string name = bsonReader.ReadName();

            if (name != "_t")
            {
                throw new PBException("error reading ZValue can't find ZValue type \"_t\"");
            }
            string typeName = bsonReader.ReadString();

            type = bsonReader.ReadBsonType();
            name = bsonReader.ReadName();
            if (name != "value")
            {
                throw new PBException("error reading ZValue can't find ZValue value \"value\"");
            }
            ZValue value = null;

            switch (typeName)
            {
            case "ZString":
                if (type != BsonType.String)
                {
                    throw new PBException("error reading ZString value is'nt a string ({0})", type);
                }
                value = new ZString(bsonReader.ReadString());
                break;

            //case "ZStringArray":
            //    if (type != BsonType.Array)
            //        throw new PBException("error reading ZStringArray value is'nt an array ({0})", type);
            //    value = new ZString(bsonReader.ReadString());
            //    break;
            case "ZInt":
                if (type != BsonType.Int32)
                {
                    throw new PBException("error reading ZInt value is'nt an int32 ({0})", type);
                }
                value = new ZInt(bsonReader.ReadInt32());
                break;

            default:
                throw new PBException("error reading ZValue type \"{0}\" is'nt a ZValue type", typeName);
            }
            type = bsonReader.ReadBsonType();
            if (type != BsonType.EndOfDocument)
            {
                throw new PBException("error reading ZValue cant find end of document ({0})", type);
            }
            bsonReader.ReadEndDocument();
            return(value);
        }
示例#4
0
 static void CheckEq(ZInt x, ZInt z)
 {
     if (x != z)
     {
         throw new Exception(String.Format(
                                 "mismatch: x={0} z={1}", x, z));
     }
 }
示例#5
0
    static ZInt RandPrime(int k)
    {
        if (k < 2)
        {
            throw new ArgumentException();
        }
        ZInt min = ZInt.One << (k - 1);
        ZInt max = ZInt.One << k;

        for (;;)
        {
            ZInt p = ZInt.MakeRand(min, max) | 1;
            if (p.IsPrime)
            {
                return(p);
            }
        }
    }
示例#6
0
    public void Run(byte[] iv,
                    byte[] data, int off, int len,
                    byte[] aad, int offAAD, int lenAAD,
                    byte[] tag, bool encrypt)
    {
        byte[] pkey = new byte[32];
        ChaCha.Run(iv, 0, pkey);
        if (encrypt)
        {
            ChaCha.Run(iv, 1, data, off, len);
        }

        ByteSwap(pkey, 0, 16);
        ZInt r = ZInt.DecodeUnsignedBE(pkey, 0, 16);

        r &= rmask;
        ZInt a = (ZInt)0;

        a = RunInner(a, r, aad, offAAD, lenAAD);
        a = RunInner(a, r, data, off, len);
        byte[] foot = new byte[16];
        foot[0]  = (byte)lenAAD;
        foot[1]  = (byte)(lenAAD >> 8);
        foot[2]  = (byte)(lenAAD >> 16);
        foot[3]  = (byte)(lenAAD >> 24);
        foot[8]  = (byte)len;
        foot[9]  = (byte)(len >> 8);
        foot[10] = (byte)(len >> 16);
        foot[11] = (byte)(len >> 24);
        a        = RunInner(a, r, foot, 0, 16);

        ByteSwap(pkey, 16, 16);
        ZInt s = ZInt.DecodeUnsignedBE(pkey, 16, 16);

        a += s;
        a.ToBytesLE(tag, 0, 16);

        if (!encrypt)
        {
            ChaCha.Run(iv, 1, data, off, len);
        }
    }
示例#7
0
    /*
     * Interpret a token as a constant value (numerical constant,
     * boolean, literal string). If the token is not such a constant,
     * the returned value is uninitialized.
     */
    internal static XValue ParseConst(string t)
    {
        if (t.Length == 0)
        {
            return(new XValue((XObject)null));
        }
        if (t == "true")
        {
            return(new XValue(XType.BOOL, 1));
        }
        if (t == "false")
        {
            return(new XValue(XType.BOOL, 0));
        }
        if (t[0] == '"')
        {
            return(new XValue(t.Substring(1)));
        }
        if (t[0] == '`')
        {
            int cp = t[1];
            if (cp > 0x7F)
            {
                throw new Exception("non-ASCII character constant");
            }
            return((byte)cp);
        }
        bool neg = false;

        if (t[0] == '+')
        {
            t = t.Substring(1);
        }
        else if (t[0] == '-')
        {
            neg = true;
            t   = t.Substring(1);
        }
        if (t.Length == 0 || t[0] < '0' || t[0] > '9')
        {
            return(new XValue((XObject)null));
        }

        XType bt  = XType.INT;
        ZInt  min = Int32.MinValue;
        ZInt  max = Int32.MaxValue;

        if (t.EndsWith("u8") || t.EndsWith("U8"))
        {
            t   = t.Substring(0, t.Length - 2);
            bt  = XType.U8;
            min = 0;
            max = Byte.MaxValue;
        }
        else if (t.EndsWith("u16") || t.EndsWith("U16"))
        {
            t   = t.Substring(0, t.Length - 3);
            bt  = XType.U16;
            min = 0;
            max = UInt16.MaxValue;
        }
        else if (t.EndsWith("u32") || t.EndsWith("U32"))
        {
            t   = t.Substring(0, t.Length - 3);
            bt  = XType.U32;
            min = 0;
            max = UInt32.MaxValue;
        }
        else if (t.EndsWith("u64") || t.EndsWith("U64"))
        {
            t   = t.Substring(0, t.Length - 3);
            bt  = XType.U64;
            min = 0;
            max = UInt64.MaxValue;
        }
        else if (t.EndsWith("i8") || t.EndsWith("I8"))
        {
            t   = t.Substring(0, t.Length - 2);
            bt  = XType.I8;
            min = SByte.MinValue;
            max = SByte.MaxValue;
        }
        else if (t.EndsWith("i16") || t.EndsWith("I16"))
        {
            t   = t.Substring(0, t.Length - 3);
            bt  = XType.I16;
            min = Int16.MinValue;
            max = Int16.MaxValue;
        }
        else if (t.EndsWith("i32") || t.EndsWith("I32"))
        {
            t   = t.Substring(0, t.Length - 3);
            bt  = XType.I32;
            min = Int32.MinValue;
            max = Int32.MaxValue;
        }
        else if (t.EndsWith("i64") || t.EndsWith("I64"))
        {
            t   = t.Substring(0, t.Length - 3);
            bt  = XType.I64;
            min = Int64.MinValue;
            max = Int64.MaxValue;
        }

        ZInt x = ZInt.Parse(t);

        if (neg)
        {
            x = -x;
        }
        if (x < min || x > max)
        {
            throw new Exception(string.Format("value {0} is out of allowed range for type {1}", x, bt.Name));
        }

        return(new XValue(bt, x.ToULong));
    }
示例#8
0
    internal static void TestModInt()
    {
        Console.Write("Test ModInt: ");
        for (int k = 2; k <= 128; k++)
        {
            for (int i = 0; i < 10; i++)
            {
                int kwlen = (k + 30) / 31;
                int kwb   = 31 * kwlen;

                ZInt p;
                if (k >= 9)
                {
                    p = ZInt.DecodeUnsignedBE(
                        BigInt.RandPrime(k));
                    if (p.BitLength != k)
                    {
                        throw new Exception(
                                  "wrong prime size");
                    }
                    if (!p.IsPrime)
                    {
                        throw new Exception(
                                  "not prime");
                    }
                }
                else
                {
                    p = RandPrime(k);
                }

                ZInt a = ZInt.MakeRand(p);
                ZInt b = ZInt.MakeRand(p);
                ZInt v = ZInt.MakeRand(k + 60);
                if (b == ZInt.Zero)
                {
                    b = ZInt.One;
                }
                byte[] ea = a.ToBytesBE();
                byte[] eb = b.ToBytesBE();
                byte[] ev = v.ToBytesBE();
                ModInt mz = new ModInt(p.ToBytesBE());
                ModInt ma = mz.Dup();
                ModInt mb = mz.Dup();

                ma.Decode(ea);
                CheckEq(ma, a);

                ma.Decode(ea);
                mb.Decode(eb);
                ma.Add(mb);
                CheckEq(ma, (a + b).Mod(p));

                ma.Decode(ea);
                mb.Decode(eb);
                ma.Sub(mb);
                CheckEq(ma, (a - b).Mod(p));

                ma.Decode(ea);
                ma.Negate();
                CheckEq(ma, (-a).Mod(p));

                ma.Decode(ea);
                mb.Decode(eb);
                ma.MontyMul(mb);
                CheckEq((ZInt.DecodeUnsignedBE(ma.Encode())
                         << kwb).Mod(p), (a * b).Mod(p));

                ma.Decode(ea);
                ma.ToMonty();
                CheckEq(ma, (a << kwb).Mod(p));
                ma.FromMonty();
                CheckEq(ma, a);

                ma.Decode(ea);
                mb.Decode(eb);
                ma.ToMonty();
                mb.ToMonty();
                ma.MontyMul(mb);
                ma.FromMonty();
                CheckEq(ma, (a * b).Mod(p));

                mb.Decode(eb);
                mb.Invert();
                ZInt r = ZInt.DecodeUnsignedBE(mb.Encode());
                CheckEq(ZInt.One, (r * b).Mod(p));

                ma.Decode(ea);
                ma.Pow(ev);
                CheckEq(ma, ZInt.ModPow(a, v, p));

                ma.DecodeReduce(ev);
                CheckEq(ma, v.Mod(p));

                mb.Decode(eb);
                ma.Set(mb);
                CheckEq(ma, b);

                ModInt mv = new ModInt(
                    ((p << 61) + 1).ToBytesBE());
                mv.Decode(ev);
                ma.Set(mv);
                CheckEq(ma, v.Mod(p));

                if (k >= 9)
                {
                    ma.Decode(ea);
                    mb.Set(ma);
                    mb.ToMonty();
                    mb.MontyMul(ma);
                    if ((int)mb.SqrtBlum() != -1)
                    {
                        throw new CryptoException(
                                  "square root failed");
                    }
                    if (!mb.Eq(ma))
                    {
                        mb.Negate();
                    }
                    CheckEq(mb, a);

                    mb.Decode(eb);
                    mb.ToMonty();
                    mb.MontySquare();
                    mb.FromMonty();
                    mb.Negate();
                    if (mb.SqrtBlum() != 0)
                    {
                        throw new CryptoException(
                                  "square root should"
                                  + " have failed");
                    }
                }
            }
            Console.Write(".");
        }
        Console.WriteLine(" done.");
    }
示例#9
0
 static void CheckEq(ModInt m, ZInt z)
 {
     CheckEq(ZInt.DecodeUnsignedBE(m.Encode()), z);
 }
示例#10
0
 private ZValue ReadZValueFromBsonDocument(BsonReader bsonReader)
 {
     // { "_t" : "ZString", "value" : "" }
     bsonReader.ReadStartDocument();
     BsonType type = bsonReader.ReadBsonType();
     if (type != BsonType.String)
         throw new PBException("error reading ZValue can't find ZValue type \"_t\"");
     string name = bsonReader.ReadName();
     if (name != "_t")
         throw new PBException("error reading ZValue can't find ZValue type \"_t\"");
     string typeName = bsonReader.ReadString();
     type = bsonReader.ReadBsonType();
     name = bsonReader.ReadName();
     if (name != "value")
         throw new PBException("error reading ZValue can't find ZValue value \"value\"");
     ZValue value = null;
     switch (typeName)
     {
         case "ZString":
             if (type != BsonType.String)
                 throw new PBException("error reading ZString value is'nt a string ({0})", type);
             value = new ZString(bsonReader.ReadString());
             break;
         //case "ZStringArray":
         //    if (type != BsonType.Array)
         //        throw new PBException("error reading ZStringArray value is'nt an array ({0})", type);
         //    value = new ZString(bsonReader.ReadString());
         //    break;
         case "ZInt":
             if (type != BsonType.Int32)
                 throw new PBException("error reading ZInt value is'nt an int32 ({0})", type);
             value = new ZInt(bsonReader.ReadInt32());
             break;
         default:
             throw new PBException("error reading ZValue type \"{0}\" is'nt a ZValue type", typeName);
     }
     type = bsonReader.ReadBsonType();
     if (type != BsonType.EndOfDocument)
         throw new PBException("error reading ZValue cant find end of document ({0})", type);
     bsonReader.ReadEndDocument();
     return value;
 }