1.PBC库介绍
PBC(Pairing-Based Cryptography Libarary)是实现双线性对运算的函数库,由Stanford大学Ben Lynn博士用C开发并开源的密码库。 PBC密码库为双线性对实现提供了接口,是基于双线性对密码体制研究的一个非常有用的辅助工具。
库的地址:http://crypto.stanford.edu/pbc/
2.PBC库安装
首先,在官网下载安装包,可以看到有多个不同的包,这里下载pbc-0.5.14.tar.gz,因为安装环境是在Linux平台。
linux下执行步骤如下:
wget https://crypto.stanford.edu/pbc/files/pbc-0.5.14.tar.gz
tar -zxvf pbc-0.5.14.tar.gz
./configure --prefix=$HOME/.local
make
make install
其中--prefix
指定了PBC库要安装的目录,您也可以指定到自己喜欢的地方。如果一切正常,您应该会在$HOME/.local
中看到新文件,包括include
、lib
和bin
三个文件夹
3.PBC库使用
- 在需要用到PBC库的源代码包含头文件
pbc/pbc.h
即可。即#include <pbc/pbc.h>
。可以看出pbc.h主要汇总了其他要包含的头文件:
#ifndef __PBC_H__
#define __PBC_H__
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h> // for intptr_t
#include <stdlib.h>
#include <gmp.h>
#if defined (__cplusplus)
extern "C" {
#endif
#include "pbc_utils.h"
#include "pbc_field.h"
#include "pbc_param.h"
#include "pbc_pairing.h"
#include "pbc_curve.h"
#include "pbc_mnt.h"
#include "pbc_a1_param.h"
#include "pbc_a_param.h"
#include "pbc_d_param.h"
#include "pbc_e_param.h"
#include "pbc_f_param.h"
#include "pbc_g_param.h"
#include "pbc_i_param.h"
#include "pbc_random.h"
#include "pbc_memory.h"
#if defined (__cplusplus)
} // extern "C"
#endif
#endif //__PBC_H__
- 编译的时候需要链接
GMP
库和PBC
库。即在gcc
或者g++
命令上加入-lgmp -lpbc
; 如果使用Cmake构建代码,在CMakeLists.txt
上加入link_libraries(gmp)
以及link_libraries(pbc)
。
test.cpp
#include "pbc.h"
int main(void)
{
/* call PBC functions */
return 0;
}
编译示例如下:
g++ -o test test.cpp -lgmp -lpbc -L/usr/local/lib/pbc
4.相关API
4.1 配对的初始化和释放
在pbc中,配对的类型为pairing_t
,初始化前需要声明变量,如pairing_t pairing
。
一般配对的初始化有三个函数:
int pairing_init_set_str(pairing_t pairing,const char * s)
int pairing_init_set_buf(pairing_t pairing,const char * s,size_t len)
void pairing_init_pbc_param(struct pairing_s *pairing, pbc_param_t p)
其中第一第二个函数直接从字符串读取,第三个使用pbc_param_t
对象初始化。一般来说第一第二个比较常用。其中pairing
为需要初始化的配对变量,s
为字符串的参数,len
为字符串的长度。
初始化的参数一般也不需要自己手写,在PBC库上已经集成了几个比较常用的配对参数。我们可以在PBC源码的param
目录上找到。论文一般都是用Type A
配对。我们可以复制param/a.param
文件的内容在代码上进行初始化即可:
#define TYPEA_PARAMS \
"type a\n" \
"q 87807107996633125224377819847540498158068831994142082" \
"1102865339926647563088022295707862517942266222142315585" \
"8769582317459277713367317481324925129998224791\n" \
"h 12016012264891146079388821366740534204802954401251311" \
"822919615131047207289359704531102844802183906537786776\n" \
"r 730750818665451621361119245571504901405976559617\n" \
"exp2 159\n" \
"exp1 107\n" \
"sign1 1\n" \
"sign0 1\n"
pairing_t pairing;
pairing_init_set_buf(pairing, TYPEA_PARAMS, strlen(TYPEA_PARAMS));
也可以使用fopen()
读取文件内容初始化:
pairing_t pairing;
char param[1024];
FILE* file = fopen("a.param", "r");
size_t count = fread(param, 1, 1024, file);
fclose(file);
if (!count) pbc_die("input error");
pairing_init_set_buf(pairing, param, count);
当不用这个配对的时候,需要调用void pairing_clear(pairing_t pairing)
释放这个变量。
4.2 元素的初始化和释放
双线性映射 e : G 1 × G 2 → G T e: G_1 \times G_2 \rightarrow G_T e:G1×G2→GT ,其涉及三个素数阶的循环群, P B C \mathrm{PBC} PBC 中称它们为 G 1 、 G 2 G_1 、 G_2 G1、G2