示例#1
0
        public void Dencrypt()
        {
            try {
                string   plain    = "Plain TextABCDEF";
                string   k1       = "0123456789ABCDEF";
                string   k2       = "io.github.odys-z";
                byte[]   iv64     = AESHelper.getRandom();
                string   iv       = AESHelper.Encode64(iv64);
                string   cypher   = AESHelper.Encrypt(plain, k1, iv64);
                string[] cypherss = AESHelper.Dencrypt(cypher, k1, iv, k2);
                Assert.AreEqual(plain, AESHelper.Decrypt(cypherss[0], k2, AESHelper.Decode64(cypherss[1])));

                Debug.WriteLine("Check this at server side:");
                Debug.WriteLine(string.Format("Cypher:\n{0}", cypherss[0]));
                Debug.WriteLine(string.Format("Key:\n{0},\nIV:\n{1}", k2, cypherss[1]));
                Debug.WriteLine(string.Format("Expacting:\n{0}", plain));

                plain    = "Слава Україні";
                cypher   = AESHelper.Encrypt(plain, k1, iv64);
                cypherss = AESHelper.Dencrypt(cypher, k1, iv, k2);
                Assert.AreEqual(plain, AESHelper.Decrypt(cypherss[0], k2, AESHelper.Decode64(cypherss[1])));
            }
            catch (Exception e) {
                Debug.WriteLine(e.ToString());
                Assert.Fail(e.Message);
            }
        }
示例#2
0
        /// <summary>
        /// Upload files to "a_attaches" table. Before files been saved, all files attached to
        /// the recid will been deleted. (This is supported by the semantic-DA samantics configuration)
        /// <p><b>FIXME:</b></p>
        /// this method used 2 round of memory copy, should implemented in stream style
        /// </summary>
        /// <param name="files"></param>
        /// <param name="busiTbl">business table to which file is attached, e.g. "a_users"</param>
        /// <param name="recid">business record Id to which file is owned, e.g. "admin"</param>
        public void AttachFiles(List <string> files, string busiTbl, string recid,
                                Action <MsgCode, AnsonResp> onOk = null, Action <MsgCode, AnsonResp> onErr = null)
        {
            AnsonMsg    jmsg = Delete(null, "a_attaches");
            AnUpdateReq del  = (AnUpdateReq)jmsg.Body(0);

            del.WhereEq("busiTbl", busiTbl)
            .WhereEq("busiId", recid);

            foreach (string file in files)
            {
                byte[] f   = File.ReadAllBytes(file);
                string fn  = Path.GetFileName(file);
                string b64 = AESHelper.Encode64(f);
                del.Post(AnInsertReq
                         .formatInsertReq(null, null, "a_attaches")
                         .Cols("attName", "busiId", "busiTbl", "uri")
                         .Nv("attName", fn)
                         .Nv("busiId", recid)
                         .Nv("busiTbl", busiTbl)
                         .Nv("uri", b64));
            }

            jmsg.Header(Header());

            Console(jmsg);

            Commit(jmsg,
                   (code, data) => {
                if (MsgCode.ok == code.code)
                {
                    if (onOk != null)
                    {
                        onOk(code, (AnsonResp)data.Body(0));
                    }
                    else
                    {
                        Utils.Logi(code.ToString());
                    }
                }
                else if (onErr != null)
                {
                    onErr(code, (AnsonResp)data.Body(0));
                }
                else
                {
                    Utils.Warn(data.ToString());
                }
            },
                   onErr: (c, err) => {
                if (onErr != null)
                {
                    onErr(c, err);
                }
                else
                {
                    Utils.Warn(string.Format(@"code: {0}, error: {1}", c, err.Msg()));
                }
            });
        }
示例#3
0
        /// <summary>
        /// Login and return a client instance (with session managed by jserv).
        /// </summary>
        /// <param name="uid"></param>
        /// <paramref name="pswdPlain">password in plain</param>
        /// <param name="device"></param>
        /// <param name="onlogin"></param>
        /// <param name="err"></param>
        /// <throws>SQLException the request makes server generate wrong SQL.</throws>
        /// <throws>SemanticException Request can not parsed correctly</throws>
        /// <throws>GeneralSecurityException  other error</throws>
        /// <throws>Exception, most likely the network failed</throws>
        /// <return>null if failed, a SessionClient instance if login succeed.</return>
        public static async Task <SessionClient> Login(string uid, string pswdPlain, string device,
                                                       OnLogin onlogin, OnError err = null)
        {
            byte[] iv   = AESHelper.getRandom();
            string iv64 = AESHelper.Encode64(iv);

            if (uid == null || pswdPlain == null)
            {
                throw new SemanticException("user id and password can not be null.");
            }

            // string tk64 = AESHelper.Encrypt("-----------" + uid, pswdPlain, iv);
            string tk64 = AESHelper.Encrypt(uid, pswdPlain, iv);

            // formatLogin: {a: "login", logid: logId, pswd: tokenB64, iv: ivB64};
            // AnsonMsg<? extends AnsonBody> reqv11 = new AnsonMsg<AnQueryReq>(Port.session);;
            AnsonMsg reqv11 = AnSessionReq.formatLogin(uid, tk64, iv64, device);

            string         url        = ServUrl(new Port(Port.session));
            HttpServClient httpClient = new HttpServClient();

            SessionClient[] inst = new SessionClient[1];
            AnsonMsg        msg  = await httpClient.Post(url, reqv11).ConfigureAwait(false);

            MsgCode code = msg.code;

            if (code != null && MsgCode.ok == code.code)
            {
                // create a logged in client
                inst[0] = new SessionClient(((AnSessionResp)msg.Body()[0]).ssInf);
                if (onlogin != null)
                {
                    // onlogin.ok(new SessionClient(((AnSessionResp)msg.Body()[0]).ssInf));
                    onlogin.ok(inst[0]);
                }

                if (AnClient.console)
                {
                    Console.WriteLine(msg.ToString());
                }
            }
            else if (err != null)
            {
                err.err(new MsgCode(code.code), ((AnsonResp)msg.Body(0)).Msg());
            }
            else
            {
                throw new SemanticException(
                          "loging failed\ncode: {0}\nerror: {1}",
                          code, ((AnsonResp)msg.Body()[0]).Msg());
            }
            return(inst[0]);
        }
示例#4
0
        /**Create request for inserting new photo.
         * <p>FIXME: introducing stream field of Anson?</p>
         * @param collId
         * @param fullpath
         * @return request
         * @throws IOException
         */
        public AlbumReq createPhoto(string collId, string fullpath)
        {
            // File p = Paths.get(fullpath);
            byte[] f   = File.ReadAllBytes(fullpath);
            string b64 = AESHelper.Encode64(f);

            this.photo            = new Photo();
            this.photo.collectId  = collId;
            this.photo.clientpath = fullpath;
            this.photo.uri        = b64;
            this.photo.pname      = Path.GetFileName(fullpath);

            this.a = A.insertPhoto;

            return(this);
        }
示例#5
0
        static void UploadTransaction(CancellationTokenSource waker, AnsonClient client, string p)
        {
            // string p = Path.get(filename);
            byte[] f   = File.ReadAllBytes(p);
            string b64 = AESHelper.Encode64(f);

            AnsonMsg    jmsg = client.Update(null, "a_users");
            AnUpdateReq upd  = (AnUpdateReq)jmsg.Body(0);

            upd.Nv("nationId", "CN")
            .WhereEq("userId", "admin")
            // .post(((UpdateReq) new UpdateReq(null, "a_attach")
            .Post(AnUpdateReq.formatDelReq(null, null, "a_attaches")
                  .WhereEq("busiTbl", "a_users")
                  .WhereEq("busiId", "admin")
                  .Post((AnInsertReq.formatInsertReq(null, null, "a_attaches")
                         .Cols("attName", "busiId", "busiTbl", "uri")
                         .Nv("attName", "-Anclient.cs Test")
                         // The parent pk can't be resulved, we must provide the value.
                         // See https://odys-z.github.io/notes/semantics/best-practices.html#fk-ins-cate
                         .Nv("busiId", "admin")
                         .Nv("busiTbl", "a_users")
                         .Nv("uri", b64))));

            jmsg.Header(client.Header());

            client.Console(jmsg);

            client.Commit(jmsg,
                          (code, data) => {
                if (MsgCode.ok == code.code)
                {
                    Utils.Logi(code.ToString());
                }
                else
                {
                    Utils.Warn(data.ToString());
                }
            },
                          onErr: (c, err) => {
                Assert.Fail(string.Format(@"code: {0}, error: {1}", c, err.Msg()));
            },
                          waker);
        }
示例#6
0
        public IList <DocsResp> syncVideos(IList <IFileDescriptor> videos, SessionInf user, OnProcess proc, ErrorCtx onErr = null)
        {
            ErrorCtx errHandler = onErr == null ? errCtx : onErr;

            DocsResp resp = null;

            try
            {
                AnsonHeader header = client.Header().act(new string[] { "album.c#", "synch", "c/photo", "multi synch" });

                IList <DocsResp> reslts = new List <DocsResp>(videos.Count);

                for (int px = 0; px < videos.Count; px++)
                {
                    IFileDescriptor p   = videos[px];
                    DocsReq         req = new DocsReq()
                                          .blockStart(p, user);

                    AnsonMsg q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req)
                                 .Header(header);

                    resp = (DocsResp)client.Commit(q, errHandler);
                    // stringchainId = resp.chainId();
                    string pth = p.fullpath();
                    if (pth != resp.Fullpath())
                    {
                        Utils.Warn("resp not reply with exactly the same path: %s", resp.Fullpath());
                    }

                    int totalBlocks = (int)((new FileInfo(pth).Length + 1) / blocksize);
                    if (proc != null)
                    {
                        proc.proc(px, totalBlocks, resp);
                    }

                    int        seq = 0;
                    FileStream ifs = File.Create(p.fullpath());
                    try
                    {
                        string b64 = AESHelper.Encode64(ifs, blocksize);
                        while (b64 != null)
                        {
                            req = new DocsReq().blockUp(seq, resp, b64, user);
                            seq++;

                            q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req)
                                .Header(header);

                            resp = (DocsResp)client.Commit(q, errHandler);
                            if (proc != null)
                            {
                                proc.proc(px, totalBlocks, resp);
                            }

                            b64 = AESHelper.Encode64(ifs, blocksize);
                        }
                        req = new DocsReq().blockEnd(resp, user);
                        q   = client.UserReq(uri, new AlbumPort(AlbumPort.album), req)
                              .Header(header);

                        resp = (DocsResp)client.Commit(q, errHandler);
                        if (proc != null)
                        {
                            proc.proc(px, totalBlocks, resp);
                        }
                    }
                    catch (Exception ex)
                    {
                        Utils.Warn(ex.Message);

                        req = new DocsReq().blockAbort(resp, user);
                        req.A(DocsReq.A.blockAbort);
                        q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req)
                            .Header(header);
                        resp = (DocsResp)client.Commit(q, errHandler);
                        if (proc != null)
                        {
                            proc.proc(px, totalBlocks, resp);
                        }

                        throw ex;
                    }
                    finally { ifs.Close(); }

                    reslts.Add(resp);
                }

                return(reslts);
            }
            catch (Exception e)
            {
                errHandler.onError(new MsgCode(MsgCode.exIo), e.GetType().Name + " " + e.Message);
            }
            return(null);
        }