
正文
linux数据库中使用MD5加密
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
MD5加密算法源码下载:https://pan.baidu.com/s/1nwyN0xV
下载完成了之后解压,得到两个文件
环境搭建:
1、把md5.h文件拷贝到/usr/include/目录下
sudo cp md5.h /usr/include
2、编译生成.o文件
gcc -fPIC -o md5.o -c md5.c -lpthread -ldl
3、编译生成.so文件
gcc -shared -fPIC -o libmd5.so md5.o -lpthread -ldl
4、把生成的.so文件拷贝都/lib/目录下,方便使用
sudo cp libmd5.so /lib/
其中我们使用到了MD5中数据加密函数
void MD5Str(char *input, unsigned char *output);
参数: input:要加密的数据
output:加密后的数据
程序mysqlite3.c如下:
#include <sqlite3.h>
#include <stdio.h>
#include <string.h>
#include "md5.h" /*定义此宏时使用回调函数查询否则只是用非回调函数查询*/
//#define CALLBACK /*定义创建表格指令IF not EXISTS:不存在,AUTOINCREMENT:自动增加主键,not NULL:不能为空*/
#define CREATE "create table IF not EXISTS passwd(id integer primary key AUTOINCREMENT,username text not NULL,password text not NULL)"
/*定义查询数据指令*/
#define SELECT "select * from passwd where username='%s' and password='%s'"
/*定义插入数据指令*/
#define INSERT "insert into passwd(username,password) values('%s','%s')" /*如果查询到多行数据, 那么这个函数就会调用多次(每一行调用一次)*/
int callback(void *arg, int col, char **value, char **name)
{
int i=;
for(i=;i<col; i++)
{
printf("%s\t", value[i]);
}
printf("\n");
return ;
} int main(void)
{ //1.打开数据库
sqlite3 *ppdb = NULL;
int ret = sqlite3_open("./passwd", &ppdb); /*我们之前要先创建一个名字叫passwd的数据库*/
if(ret != SQLITE_OK)
{
perror("open fail");
return -;
}
sqlite3_exec(ppdb,CREATE,NULL,NULL,NULL); /*创建一个表格*/
char temp[];
char temp1[];
char insert[strlen(temp)+strlen(temp1)+]; /*这里的数组要给大一点,因为等下加密的时候会得到一串很长的数据*/
printf("please input your username:");
scanf("%s",temp);
printf("please input your password:");
scanf("%s",temp1);
MD5Str(temp1,temp1);/*把输入的密码使用md5加密存储在数据库表格中*/
printf("1111\n"); sprintf(insert,INSERT,temp,temp1);/*打包数据,准备插入到表格中*/ sqlite3_exec(ppdb,insert,NULL,NULL,NULL); char username[];
char password[];
printf("input username:");
scanf("%s",username);
printf("input password:");
scanf("%s",password); MD5Str(password,password);/*把输入的密码使用md5加密之后与数据库表格中的密码匹对*/
char sql[strlen(SELECT)+strlen(username)+strlen(password)]; /*打包一个字符串,将SELECT字符串放到sql中,username和password这两个变量放大SELECT中*/
sprintf(sql,SELECT,username,password); #ifdef CALLBACK
//回调查询
char *selectsql = "select * from myname";
ret = sqlite3_exec(ppdb, selectsql, callback, NULL, NULL);
if(ret != SQLITE_OK)
{
perror("create fail");
sqlite3_close(ppdb);
return -;
} //非回调查询
#else
char **result = NULL;
int row = ;
int col = ;
char *error = NULL;
ret = sqlite3_get_table(ppdb,sql,&result,&row,&col,&error);
if(ret != SQLITE_OK)
{
perror("get table fail");
return -;
} int i=, j=;
for(i=;i<row+;i++)
{
for(j=;j<col;j++)
{
printf("%s\t",result[j+i*col]);
}
printf("\n");
} if(row > ) /*数据匹配成功*/
printf("checked OK\n");
else /*数据匹配失败*/
printf("fail\n");
sqlite3_free_table(result);//释放结果
#endif sqlite3_close(ppdb);
return ;
}
我们先要创建一个名字叫passwd数据库,如果不懂创建可以看看我的这篇文章:linux数据库环境搭建
sqlite3 passwd
接着我们编译程序
gcc -o mysqlite3 mysqlite3.c -lsqlite3 -lmd5
运行结果如下:








