Added and fixed.

This commit is contained in:
Saturneic 2019-02-04 00:26:45 +08:00
parent 0c3749ad99
commit 726ee78691
17 changed files with 9621 additions and 71 deletions

View File

@ -20,6 +20,8 @@
92C34C272205C63A00AB38D3 /* server.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9277A15821FD725F009C5F11 /* server.cpp */; };
92C34C282205C94600AB38D3 /* addr.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9277A15221FD725F009C5F11 /* addr.cpp */; };
92C34C292205C95F00AB38D3 /* socket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9277A15321FD725F009C5F11 /* socket.cpp */; };
92C34C37220747A200AB38D3 /* sha1.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 92C34C36220747A200AB38D3 /* sha1.cpp */; };
92C34C3B22074B6500AB38D3 /* rsa.c in Sources */ = {isa = PBXBuildFile; fileRef = 92C34C3A22074B6500AB38D3 /* rsa.c */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
@ -63,6 +65,10 @@
9277A18D22007758009C5F11 /* sql.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = sql.h; path = include/sql.h; sourceTree = "<group>"; };
9277A18E220077CC009C5F11 /* cproj.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = cproj.h; path = include/cproj.h; sourceTree = "<group>"; };
9277A18F220079DB009C5F11 /* cproj_proj.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = cproj_proj.cpp; path = src/cproj_proj.cpp; sourceTree = "<group>"; };
92C34C36220747A200AB38D3 /* sha1.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = sha1.cpp; path = src/sha1.cpp; sourceTree = "<group>"; };
92C34C38220747B300AB38D3 /* sha1.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = sha1.h; path = include/sha1.h; sourceTree = "<group>"; };
92C34C3922074B5B00AB38D3 /* rsa.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = rsa.h; path = include/rsa.h; sourceTree = "<group>"; };
92C34C3A22074B6500AB38D3 /* rsa.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = rsa.c; path = src/rsa.c; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@ -106,11 +112,13 @@
925A13AA21EC989500CBD427 /* include */ = {
isa = PBXGroup;
children = (
92C34C3922074B5B00AB38D3 /* rsa.h */,
9277A18E220077CC009C5F11 /* cproj.h */,
9277A18D22007758009C5F11 /* sql.h */,
9277A14C21FD7246009C5F11 /* clock.h */,
9277A14621FD7246009C5F11 /* cmap.h */,
9277A14921FD7246009C5F11 /* compute.h */,
92C34C38220747B300AB38D3 /* sha1.h */,
9277A14B21FD7246009C5F11 /* cpart.h */,
9277A14A21FD7246009C5F11 /* cthread.h */,
9277A14D21FD7246009C5F11 /* md5.h */,
@ -126,11 +134,13 @@
9277A15121FD724C009C5F11 /* src */ = {
isa = PBXGroup;
children = (
92C34C3A22074B6500AB38D3 /* rsa.c */,
9277A15221FD725F009C5F11 /* addr.cpp */,
9277A15C21FD725F009C5F11 /* clock.cpp */,
9277A15921FD725F009C5F11 /* cmap.cpp */,
9277A15A21FD725F009C5F11 /* cpart.cpp */,
9277A15521FD725F009C5F11 /* cproj_cpt.cpp */,
92C34C36220747A200AB38D3 /* sha1.cpp */,
9277A15721FD725F009C5F11 /* cthread.cpp */,
9277A15621FD725F009C5F11 /* main.cpp */,
9277A15421FD725F009C5F11 /* md5.cpp */,
@ -213,7 +223,9 @@
9277A16621FD725F009C5F11 /* cpart.cpp in Sources */,
9277A16121FD725F009C5F11 /* cproj_cpt.cpp in Sources */,
9277A190220079DB009C5F11 /* cproj_proj.cpp in Sources */,
92C34C37220747A200AB38D3 /* sha1.cpp in Sources */,
9277A16021FD725F009C5F11 /* md5.cpp in Sources */,
92C34C3B22074B6500AB38D3 /* rsa.c in Sources */,
9277A16521FD725F009C5F11 /* cmap.cpp in Sources */,
9277A16221FD725F009C5F11 /* main.cpp in Sources */,
92C34C272205C63A00AB38D3 /* server.cpp in Sources */,

8771
data/primes.txt Executable file

File diff suppressed because it is too large Load Diff

View File

@ -15,6 +15,7 @@
struct clock_register{
void *(*func)(void *);
bool if_thread;
bool if_reset = false;
int click;
int rawclick;
void *arg;
@ -23,7 +24,6 @@ struct clock_register{
struct clock_thread_info{
uint32_t tid = 0;
pthread_t pht = 0;
bool if_reset = false;
void *args = NULL;
clock_register *pcr;
};
@ -36,7 +36,7 @@ void setThreadsClock(void);
void threadsClock(int);
//时钟线程完结前调用此函数进行标记
void clockThreadFinish(uint32_t tid);
void newClock(clock_register ncr);
void newClock(clock_register *pncr);
#endif /* clock_h */

View File

@ -47,6 +47,14 @@ struct stn_read{
//配置文件通用方法类
class setting_file{
public:
// 检查名字是否合法
static bool if_name_illegal(string str){
for(auto c:str){
if(!if_illegal(c)) return false;
}
return true;
}
protected:
// 检查路径或文件
void check_paths(string main_path, vector<string> paths){
@ -55,17 +63,10 @@ protected:
}
}
// 检查字符是否合法
bool if_illegal(char c){
static bool if_illegal(char c){
if(isalnum(c) || c == '_') return true;
else return false;
}
// 检查名字是否合法
bool if_name_illegal(string str){
for(auto c:str){
if(!if_illegal(c)) return false;
}
return true;
}
// 寻找保留字
bool search_key(ifstream &ifsfile,string key){
string line;

View File

@ -38,6 +38,8 @@ public:
struct sockaddr *RawObj(void);
void SetIpv4(void);
void SetIpv6(void);
static bool checkValidIP(string ipaddr);
};
//服务器套接字类

39
include/rsa.h Executable file
View File

@ -0,0 +1,39 @@
#ifndef __RSA_H__
#define __RSA_H__
#include <stdint.h>
// This is the header file for the library librsaencrypt.a
// Change this line to the file you'd like to use as a source of primes.
// The format of the file should be one prime per line.
char *PRIME_SOURCE_FILE = "primes.txt";
struct public_key_class{
long long modulus;
long long exponent;
};
struct private_key_class{
long long modulus;
long long exponent;
};
// This function generates public and private keys, then stores them in the structures you
// provide pointers to. The 3rd argument should be the text PRIME_SOURCE_FILE to have it use
// the location specified above in this header.
void rsa_gen_keys(struct public_key_class *pub, struct private_key_class *priv, const char *PRIME_SOURCE_FILE);
// This function will encrypt the data pointed to by message. It returns a pointer to a heap
// array containing the encrypted data, or NULL upon failure. This pointer should be freed when
// you are finished. The encrypted data will be 8 times as large as the original data.
long long *rsa_encrypt(const char *message, const unsigned long message_size, const struct public_key_class *pub);
// This function will decrypt the data pointed to by message. It returns a pointer to a heap
// array containing the decrypted data, or NULL upon failure. This pointer should be freed when
// you are finished. The variable message_size is the size in bytes of the encrypted message.
// The decrypted data will be 1/8th the size of the encrypted data.
char *rsa_decrypt(const long long *message, const unsigned long message_size, const struct private_key_class *pub);
#endif

View File

@ -25,6 +25,7 @@ struct compute_result{
vector<int> *fargs_out;
};
//通用数据包类
class packet{
public:
@ -54,6 +55,14 @@ public:
}
};
struct server_info{
string tag;
string name;
string msqes_ip;
int msqes_prot;
string key;
};
//通用服务器类
class Server{
protected:
@ -61,6 +70,7 @@ protected:
vector<packet> packets_in;
// 缓存带标签的二进制串管理结构
vector<raw_data> rawdata_in;
struct server_info tsi;
public:
// 服务器类的接收套接字对象与发送套接字对象
SocketUDPServer socket;

44
include/sha1.h Executable file
View File

@ -0,0 +1,44 @@
#ifndef SHA1_H
#define SHA1_H
/*
SHA-1 in C
By Steve Reid <steve@edmweb.com>
100% Public Domain
*/
#include "stdint.h"
typedef struct
{
uint32_t state[5];
uint32_t count[2];
unsigned char buffer[64];
} SHA1_CTX;
void SHA1Transform(
uint32_t state[5],
const unsigned char buffer[64]
);
void SHA1Init(
SHA1_CTX * context
);
void SHA1Update(
SHA1_CTX * context,
const unsigned char *data,
uint32_t len
);
void SHA1Final(
unsigned char digest[20],
SHA1_CTX * context
);
void SHA1(
char *hash_out,
const char *str,
int len);
#endif /* SHA1_H */

View File

@ -37,6 +37,8 @@ namespace sql {
int insert_info(sqlite3 *psql, sqlite3_stmt **psqlsmt, string table_name, vector<pair<string, string>>value);
// 生成字符串格式的数据
string string_type(string str);
// 输出错误信息
void printError(sqlite3 *psql);
}
#endif /* sql_h */

View File

@ -73,3 +73,16 @@ void Addr::SetIpv6(void){
address.sin_family = AF_INET6;
SetSize();
}
bool Addr::checkValidIP(string ipaddr){
char temp[31];
int a,b,c,d;
if (sscanf(ipaddr.data(), "%d.%d.%d.%d ", &a, &b, &c, &d) == 4 && a >= 0 && a <= 255 && b >= 0 && b <= 255 && c >= 0 && c <= 255 && d >= 0 && d <= 255){
sprintf(temp, "%d.%d.%d.%d", a, b, c, d); //把格式化的数据写入字符串temp
if (!strcmp(temp, ipaddr.data())) return true; //success
else return false;
}
else return false;
return true;
}

View File

@ -13,19 +13,14 @@
int main(int argc, char *argv[])
{
try {
CNodeServer client(9049,"127.0.0.1",9048);
Server BServer(1081,"127.0.0.1",9048);
vector<int> fargs = {1,0,0,1};
vector<void *>args;
CPart::addArg<double>(&args, 12.63);
CPart::addArg<int>(&args, 10);
CPart::addArg<int>(&args, 6);
CPart::addArg<double>(&args, 8.2);
struct compute_result cpur = {"Test",&args,&args,&fargs,&fargs};
packet pkt = client.CPURS2Packet(cpur);
raw_data rwd = client.Packet2Rawdata(pkt);
client.SignedRawdata(&rwd, "RSTR");
raw_data rwd;
rwd.setData("Hello");
BServer.SignedRawdata(&rwd, "TEXT");
while (1) {
client.SentRawdata(&rwd);
BServer.SentRawdata(&rwd);
usleep(1000);
}

View File

@ -11,10 +11,12 @@
#define CLOCKESE 30
list<clock_register> clocks_list;
list<clock_register *> clocks_list,reset_clocks;
map<uint32_t,clock_thread_info *> clocks_thread_map;
list<uint32_t> clock_thread_finished;
static struct itimerval oitrl, itrl;
uint32_t tid_r = 0;
static uint64_t clock_erase = CLOCKESE;
@ -33,63 +35,69 @@ void setThreadsClock(void){
setitimer(ITIMER_REAL, &itrl, &oitrl);
}
void newClock(clock_register ncr){
clocks_list.push_back(ncr);
void newClock(clock_register *pncr){
clocks_list.push_back(pncr);
}
//时钟滴答调用函数
void threadsClock(int n){
// 删除到期时钟
if(clock_erase == 0){
for(auto i = clocks_list.begin(); i != clocks_list.end();){
if(i->click == -1) i = clocks_list.erase(i);
else i++;
}
// 重设总滴答数
clock_erase = CLOCKESE;
}
else clock_erase--;
// 处理已完成线程
for(auto tid : clock_thread_finished){
clock_thread_info *tcti = clocks_thread_map.find(tid)->second;
pthread_join(tcti->pht,NULL);
pthread_detach(tcti->pht);
clocks_thread_map.erase(clocks_thread_map.find(tid));
// 如果时钟需要重置
if(tcti->if_reset){
clock_register ncr = *tcti->pcr;
ncr.click = ncr.rawclick;
newClock(ncr);
}
delete tcti;
}
clock_thread_finished.clear();
// 删除到期时钟
if(clock_erase == 0){
printf("Cleaning clocks.\n");
clocks_list.remove_if([](clock_register *pclock){return pclock == NULL;});
// 重设总滴答数
clock_erase = CLOCKESE;
}
else clock_erase--;
// 处理时钟列表
for(auto &clock : clocks_list){
if(clock.click == 0){
if(clock.if_thread){
clock_thread_info *pncti = new clock_thread_info();
pncti->args = clock.arg;
pncti->pcr = &clock;
pncti->tid = (uint32_t)clocks_thread_map.size()+1;
clocks_thread_map.insert({pncti->tid,pncti});
pthread_create(&pncti->pht, NULL, clock.func, pncti);
for(auto &pclock : clocks_list){
if(pclock == NULL) continue;
if(pclock->click == 0){
clock_thread_info *pncti = new clock_thread_info();
pncti->args = pclock->arg;
pncti->tid = tid_r++;
pclock->if_thread = 1;
clocks_thread_map.insert({pncti->tid,pncti});
pthread_create(&pncti->pht, NULL, pclock->func, pncti);
// 标记时钟到期
if(pclock->if_reset){
pclock->click = pclock->rawclick;
}
else{
clock.func(clock.arg);
delete pclock;
pclock = NULL;
}
// 标记时钟到期
clock.click = -1;
}
else if(clock.click > 0){
clock.click--;
else if(pclock->click > 0){
pclock->click--;
}
}
}
void clockThreadFinish(uint32_t tid){
// 屏蔽时钟信号
sigset_t sigs;
sigemptyset(&sigs);
sigaddset(&sigs,SIGALRM);
sigprocmask(SIG_BLOCK,&sigs,0);
clock_thread_finished.push_back(tid);
sigprocmask(SIG_UNBLOCK,&sigs,0);
}

View File

@ -18,13 +18,30 @@
int update(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int construct(string instruct,vector<string> &config, vector<string> &lconfig, vector<string> &target);
int server(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int init(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int set(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
struct instructions{
int (*unpack)(string instruct,vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*construct)(string instruct,vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*update)(string instruct,vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*server)(string instruct,vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*unpack)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*construct)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*update)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*server)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*set)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*init)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
};
namespace error {
void printError(string error_info){
printf("\033[31mError: %s\n\033[0m",error_info.data());
}
void printWarning(string warning_info){
printf("\033[33mWarning: %s\n\033[0m",warning_info.data());
}
void printSuccess(string succes_info){
printf("\033[32m%s\n\033[0m",succes_info.data());
}
}
int main(int argc, const char *argv[]){
// 命令
string instruct;
@ -39,6 +56,8 @@ int main(int argc, const char *argv[]){
istns.construct = construct;
istns.update = update;
istns.server = server;
istns.init = init;
istns.set = set;
// 解析命令
int if_instruct = 1;
@ -63,18 +82,26 @@ int main(int argc, const char *argv[]){
// 处理命令
if(instruct == "construct"){
if(istns.construct != nullptr) istns.construct(instruct,config,long_config,target);
else printf("Function not found.\n");
else error::printError("Function not found.");
}
else if (instruct == "update"){
if(istns.update != nullptr) istns.update(instruct,config,long_config,target);
else printf("Function not found.\n");
else error::printError("Function not found.");
}
else if (instruct == "server"){
if(istns.update != nullptr) istns.server(instruct,config,long_config,target);
else printf("Function not found.\n");
else error::printError("Function not found.");
}
else if (instruct == "init"){
if(istns.update != nullptr) istns.init(instruct,config,long_config,target);
else error::printError("Function not found.");
}
else if (instruct == "set"){
if(istns.update != nullptr) istns.set(instruct,config,long_config,target);
else error::printError("Function not found.");
}
else{
printf("Instruction \"%s\" doesn't make sense.\n",instruct.data());
printf("\033[33mInstruction \"%s\" doesn't make sense.\n\033[0m",instruct.data());
}
return 0;
@ -87,11 +114,136 @@ bool config_search(vector<string> &configs,string tfg){
return false;
}
int init(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
sqlite3_open("info.db", &psql);
const char *pzTail;
try {
sql::table_create(psql, "server_info", {
{"name","TEXT"},
{"tag","TEXT"},
{"admin_key_sha1","TEXT"},
{"msqes_ip","TEXT"},
{"msqes_port","INT"},
{"msqes_key","TEXT"},
{"msqes_rsa_public","TEXT"},
});
sql::table_create(psql, "sqes_info", {
{"sqes_ip","TEXT PRIMARY KEY"},
{"sqes_port","INT"},
{"sqes_key","TEXT"},
{"rsa_public","TEXT"},
});
} catch (const char *error_info) {
if(!strcmp(error_info, "fail to create table")){
if(!config_search(configs, "-f")){
printf("\033[33mWarning: Have Already run init process.Try configure -f to continue.\n\033[0m");
return 0;
}
else{
string sql_quote = "DELETE FROM server_info;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
int rtn = sqlite3_step(psqlsmt);
if(rtn == SQLITE_DONE){
}
else{
const char *error = sqlite3_errmsg(psql);
int errorcode = sqlite3_extended_errcode(psql);
printf("\033[31mSQL Error: [%d]%s\n\033[0m",errorcode,error);
throw error;
}
sqlite3_finalize(psqlsmt);
}
}
}
sql::insert_info(psql, &psqlsmt, "server_info", {
{"name","?1"},
{"tag","?2"}
});
if(setting_file::if_name_illegal(targets[0]));
else{
error::printError("Args(name) abnormal.");
}
if(setting_file::if_name_illegal(targets[1]));
else{
error::printError("Args(tag) abnormal.");
}
sqlite3_bind_text(psqlsmt, 1, targets[0].data(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(psqlsmt, 2, targets[1].data(), -1, SQLITE_TRANSIENT);
int rtn = sqlite3_step(psqlsmt);
if(rtn == SQLITE_DONE){
}
else throw "sql writes error";
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return 0;
}
int set(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
const char *pzTail;
if(sqlite3_open("info.db", &psql) == SQLITE_ERROR){
sql::printError(psql);
}
string sql_quote = "SELECT count(*) FROM sqlite_master WHERE name = 'server_info';";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_step(psqlsmt);
int if_find = sqlite3_column_int(psqlsmt, 0);
if(if_find);
else{
error::printError("Couldn't do set before init process.");
return -1;
}
sqlite3_finalize(psqlsmt);
if(targets[0] == "square"){
sql_quote = "UPDATE server_info SET msqes_ip = ?1, msqes_port = ?2 WHERE rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
if(!Addr::checkValidIP(targets[1])){
error::printError("Args(ipaddr) abnomal.");
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return -1;
}
sqlite3_bind_text(psqlsmt, 1, targets[1].data(), -1, SQLITE_TRANSIENT);
stringstream ss;
ss<<targets[2];
int port;
ss>>port;
if(port > 0 && port <= 65535);
else{
error::printError("Args(port) abnomal.");
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return -1;
}
sqlite3_bind_int(psqlsmt, 2, port);
int rtn = sqlite3_step(psqlsmt);
if(rtn != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
}
else if (targets[1] == "key"){
}
error::printSuccess("Succeed.");
sqlite3_close(psql);
return 0;
}
int server(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
initClock();
setThreadsClock();
Server nsvr;
setServerClock(&nsvr, 2);
setServerClock(&nsvr, 3);
while(1) usleep(10000);
return 0;
}

194
src/rsa.c Executable file
View File

@ -0,0 +1,194 @@
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
char buffer[1024];
const int MAX_DIGITS = 50;
int i,j = 0;
struct public_key_class{
long long modulus;
long long exponent;
};
struct private_key_class{
long long modulus;
long long exponent;
};
// This should totally be in the math library.
long long gcd(long long a, long long b)
{
long long c;
while ( a != 0 ) {
c = a; a = b%a; b = c;
}
return b;
}
long long ExtEuclid(long long a, long long b)
{
long long x = 0, y = 1, u = 1, v = 0, gcd = b, m, n, q, r;
while (a!=0) {
q = gcd/a; r = gcd % a;
m = x-u*q; n = y-v*q;
gcd = a; a = r; x = u; y = v; u = m; v = n;
}
return y;
}
long long rsa_modExp(long long b, long long e, long long m)
{
if (b < 0 || e < 0 || m <= 0){
exit(1);
}
b = b % m;
if(e == 0) return 1;
if(e == 1) return b;
if( e % 2 == 0){
return ( rsa_modExp(b * b % m, e/2, m) % m );
}
else{
return ( b * rsa_modExp(b, (e-1), m) % m );
}
}
// Calling this function will generate a public and private key and store them in the pointers
// it is given.
void rsa_gen_keys(struct public_key_class *pub, struct private_key_class *priv, char *PRIME_SOURCE_FILE)
{
FILE *primes_list;
if(!(primes_list = fopen(PRIME_SOURCE_FILE, "r"))){
fprintf(stderr, "Problem reading %s\n", PRIME_SOURCE_FILE);
exit(1);
}
// count number of primes in the list
long long prime_count = 0;
do{
size_t bytes_read = fread(buffer,1,sizeof(buffer)-1, primes_list);
buffer[bytes_read] = '\0';
for (i=0 ; buffer[i]; i++){
if (buffer[i] == '\n'){
prime_count++;
}
}
}
while(feof(primes_list) == 0);
// choose random primes from the list, store them as p,q
long long p = 0;
long long q = 0;
long long e = powl(2, 8) + 1;
long long d = 0;
char prime_buffer[MAX_DIGITS];
long long max = 0;
long long phi_max = 0;
srand((unsigned int)time(NULL));
do{
// a and b are the positions of p and q in the list
int a = (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
int b = (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
// here we find the prime at position a, store it as p
rewind(primes_list);
for(i=0; i < a + 1; i++){
// for(j=0; j < MAX_DIGITS; j++){
// prime_buffer[j] = 0;
// }
fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
}
p = atol(prime_buffer);
// here we find the prime at position b, store it as q
rewind(primes_list);
for(i=0; i < b + 1; i++){
for(j=0; j < MAX_DIGITS; j++){
prime_buffer[j] = 0;
}
fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
}
q = atol(prime_buffer);
max = p*q;
phi_max = (p-1)*(q-1);
}
while(!(p && q) || (p == q) || (gcd(phi_max, e) != 1));
// Next, we need to choose a,b, so that a*max+b*e = gcd(max,e). We actually only need b
// here, and in keeping with the usual notation of RSA we'll call it d. We'd also like
// to make sure we get a representation of d as positive, hence the while loop.
d = ExtEuclid(phi_max,e);
while(d < 0){
d = d+phi_max;
}
printf("primes are %lld and %lld\n",(long long)p, (long long )q);
// We now store the public / private keys in the appropriate structs
pub->modulus = max;
pub->exponent = e;
priv->modulus = max;
priv->exponent = d;
}
long long *rsa_encrypt(const char *message, const unsigned long message_size,
const struct public_key_class *pub)
{
long long *encrypted = malloc(sizeof(long long)*message_size);
if(encrypted == NULL){
fprintf(stderr,
"Error: Heap allocation failed.\n");
return NULL;
}
long long i = 0;
for(i=0; i < message_size; i++){
encrypted[i] = rsa_modExp(message[i], pub->exponent, pub->modulus);
}
return encrypted;
}
char *rsa_decrypt(const long long *message,
const unsigned long message_size,
const struct private_key_class *priv)
{
if(message_size % sizeof(long long) != 0){
fprintf(stderr,
"Error: message_size is not divisible by %d, so cannot be output of rsa_encrypt\n", (int)sizeof(long long));
return NULL;
}
// We allocate space to do the decryption (temp) and space for the output as a char array
// (decrypted)
char *decrypted = malloc(message_size/sizeof(long long));
char *temp = malloc(message_size);
if((decrypted == NULL) || (temp == NULL)){
fprintf(stderr,
"Error: Heap allocation failed.\n");
return NULL;
}
// Now we go through each 8-byte chunk and decrypt it.
long long i = 0;
for(i=0; i < message_size/8; i++){
temp[i] = rsa_modExp(message[i], priv->exponent, priv->modulus);
}
// The result should be a number in the char range, which gives back the original byte.
// We put that into decrypted, then return.
for(i=0; i < message_size/8; i++){
decrypted[i] = temp[i];
}
free(temp);
return decrypted;
}

View File

@ -12,13 +12,14 @@
extern list<clock_register> clocks_list;
void setServerClock(Server *psvr, int clicks){
clock_register ncr;
ncr.if_thread = true;
ncr.click = 3;
ncr.rawclick = 3;
ncr.func = serverDeamon;
ncr.arg = (void *)psvr;
clocks_list.push_back(ncr);
clock_register *pncr = new clock_register();
pncr->if_thread = true;
pncr->if_reset = true;
pncr->click = clicks;
pncr->rawclick = clicks;
pncr->func = serverDeamon;
pncr->arg = (void *)psvr;
newClock(pncr);
}
Server::Server(int port, string send_ip,int send_port):socket(port),send_socket(send_ip,send_port){
@ -213,6 +214,7 @@ raw_data Server::ProcessSignedRawMsg(char *p_rdt, ssize_t size){
}
void *serverDeamon(void *pvcti){
clock_thread_info *pcti = (clock_thread_info *) pvcti;
Server *psvr = (Server *) pcti->args;
//cout<<"Server Deamon Checked."<<endl;
@ -225,15 +227,15 @@ void *serverDeamon(void *pvcti){
do{
tlen = psvr->socket.RecvRAW(&str);
if(tlen > 0){
// 记录有效数据包
// 记录有效数据包
if(Server::CheckRawMsg(str, tlen)){
printf("Get\n");
raw_data trdt = Server::ProcessSignedRawMsg(str, tlen);
psvr->rawdata_in.push_back(trdt);
}
}
free(str);
}while (tlen && prm-- > 0);
pcti->if_reset = true;
clockThreadFinish(pcti->tid);
pthread_exit(NULL);
}

296
src/sha1.cpp Executable file
View File

@ -0,0 +1,296 @@
/*
SHA-1 in C
By Steve Reid <steve@edmweb.com>
100% Public Domain
Test Vectors (from FIPS PUB 180-1)
"abc"
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
A million repetitions of "a"
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/
/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */
/* #define SHA1HANDSOFF * Copies data before messing with it. */
#define SHA1HANDSOFF
#include <stdio.h>
#include <string.h>
/* for uint32_t */
#include <stdint.h>
#include "sha1.h"
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
/* blk0() and blk() perform the initial expand. */
/* I got the idea of expanding during the round function from SSLeay */
#if BYTE_ORDER == LITTLE_ENDIAN
#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
|(rol(block->l[i],8)&0x00FF00FF))
#elif BYTE_ORDER == BIG_ENDIAN
#define blk0(i) block->l[i]
#else
#error "Endianness not defined!"
#endif
#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
^block->l[(i+2)&15]^block->l[i&15],1))
/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
/* Hash a single 512-bit block. This is the core of the algorithm. */
void SHA1Transform(
uint32_t state[5],
const unsigned char buffer[64]
)
{
uint32_t a, b, c, d, e;
typedef union
{
unsigned char c[64];
uint32_t l[16];
} CHAR64LONG16;
#ifdef SHA1HANDSOFF
CHAR64LONG16 block[1]; /* use array to appear as a pointer */
memcpy(block, buffer, 64);
#else
/* The following had better never be used because it causes the
* pointer-to-const buffer to be cast into a pointer to non-const.
* And the result is written through. I threw a "const" in, hoping
* this will cause a diagnostic.
*/
CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer;
#endif
/* Copy context->state[] to working vars */
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
/* 4 rounds of 20 operations each. Loop unrolled. */
R0(a, b, c, d, e, 0);
R0(e, a, b, c, d, 1);
R0(d, e, a, b, c, 2);
R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4);
R0(a, b, c, d, e, 5);
R0(e, a, b, c, d, 6);
R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8);
R0(b, c, d, e, a, 9);
R0(a, b, c, d, e, 10);
R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12);
R0(c, d, e, a, b, 13);
R0(b, c, d, e, a, 14);
R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16);
R1(d, e, a, b, c, 17);
R1(c, d, e, a, b, 18);
R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20);
R2(e, a, b, c, d, 21);
R2(d, e, a, b, c, 22);
R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24);
R2(a, b, c, d, e, 25);
R2(e, a, b, c, d, 26);
R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28);
R2(b, c, d, e, a, 29);
R2(a, b, c, d, e, 30);
R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32);
R2(c, d, e, a, b, 33);
R2(b, c, d, e, a, 34);
R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36);
R2(d, e, a, b, c, 37);
R2(c, d, e, a, b, 38);
R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40);
R3(e, a, b, c, d, 41);
R3(d, e, a, b, c, 42);
R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44);
R3(a, b, c, d, e, 45);
R3(e, a, b, c, d, 46);
R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48);
R3(b, c, d, e, a, 49);
R3(a, b, c, d, e, 50);
R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52);
R3(c, d, e, a, b, 53);
R3(b, c, d, e, a, 54);
R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56);
R3(d, e, a, b, c, 57);
R3(c, d, e, a, b, 58);
R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60);
R4(e, a, b, c, d, 61);
R4(d, e, a, b, c, 62);
R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64);
R4(a, b, c, d, e, 65);
R4(e, a, b, c, d, 66);
R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68);
R4(b, c, d, e, a, 69);
R4(a, b, c, d, e, 70);
R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72);
R4(c, d, e, a, b, 73);
R4(b, c, d, e, a, 74);
R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76);
R4(d, e, a, b, c, 77);
R4(c, d, e, a, b, 78);
R4(b, c, d, e, a, 79);
/* Add the working vars back into context.state[] */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
/* Wipe variables */
a = b = c = d = e = 0;
#ifdef SHA1HANDSOFF
memset(block, '\0', sizeof(block));
#endif
}
/* SHA1Init - Initialize new context */
void SHA1Init(
SHA1_CTX * context
)
{
/* SHA1 initialization constants */
context->state[0] = 0x67452301;
context->state[1] = 0xEFCDAB89;
context->state[2] = 0x98BADCFE;
context->state[3] = 0x10325476;
context->state[4] = 0xC3D2E1F0;
context->count[0] = context->count[1] = 0;
}
/* Run your data through this. */
void SHA1Update(
SHA1_CTX * context,
const unsigned char *data,
uint32_t len
)
{
uint32_t i;
uint32_t j;
j = context->count[0];
if ((context->count[0] += len << 3) < j)
context->count[1]++;
context->count[1] += (len >> 29);
j = (j >> 3) & 63;
if ((j + len) > 63)
{
memcpy(&context->buffer[j], data, (i = 64 - j));
SHA1Transform(context->state, context->buffer);
for (; i + 63 < len; i += 64)
{
SHA1Transform(context->state, &data[i]);
}
j = 0;
}
else
i = 0;
memcpy(&context->buffer[j], &data[i], len - i);
}
/* Add padding and return the message digest. */
void SHA1Final(
unsigned char digest[20],
SHA1_CTX * context
)
{
unsigned i;
unsigned char finalcount[8];
unsigned char c;
#if 0 /* untested "improvement" by DHR */
/* Convert context->count to a sequence of bytes
* in finalcount. Second element first, but
* big-endian order within element.
* But we do it all backwards.
*/
unsigned char *fcp = &finalcount[8];
for (i = 0; i < 2; i++)
{
uint32_t t = context->count[i];
int j;
for (j = 0; j < 4; t >>= 8, j++)
*--fcp = (unsigned char) t}
#else
for (i = 0; i < 8; i++)
{
finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */
}
#endif
c = 0200;
SHA1Update(context, &c, 1);
while ((context->count[0] & 504) != 448)
{
c = 0000;
SHA1Update(context, &c, 1);
}
SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
for (i = 0; i < 20; i++)
{
digest[i] = (unsigned char)
((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
/* Wipe variables */
memset(context, '\0', sizeof(*context));
memset(&finalcount, '\0', sizeof(finalcount));
}
void SHA1(
char *hash_out,
const char *str,
int len)
{
SHA1_CTX ctx;
unsigned int ii;
SHA1Init(&ctx);
for (ii=0; ii<len; ii+=1)
SHA1Update(&ctx, (const unsigned char*)str + ii, 1);
SHA1Final((unsigned char *)hash_out, &ctx);
hash_out[20] = '\0';
}

View File

@ -123,8 +123,17 @@ namespace sql {
}
}
string string_type(string str){
return "\'"+str+"\'";
}
void printError(sqlite3 *psql){
if(psql != nullptr){
const char *error = sqlite3_errmsg(psql);
int errorcode = sqlite3_extended_errcode(psql);
printf("\033[31mSQL Error: [%d]%s\n\033[0m",errorcode,error);
}
}
}