x509.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. /******************************************************************************
  2. 版权所有:
  3. 文件名称: base64.c
  4. 文件版本: 01.01
  5. 创建作者: xxxxxx
  6. 创建日期: 2015-07-04
  7. 功能说明: base64解码实现文件.
  8. 其它说明:
  9. 修改记录:
  10. */
  11. /*
  12. X.509证书的结构
  13. 1、X.509证书基本部分
  14. 1.1. 版本号.
  15. 标识证书的版本(版本1、版本2或是版本3)。
  16. 1.2. 序列号
  17. 标识证书的唯一整数,由证书颁发者分配的本证书的唯一标识符。
  18. 1.3. 签名
  19. 用于签证书的算法标识,由对象标识符加上相关的参数组成,用于说明本证书所用的数字签名算法。例如,SHA-1和RSA的对象标识符就用来说明该数字签名是利用RSA对SHA-1杂凑加密。
  20. 1.4. 颁发者
  21. 证书颁发者的可识别名(DN)。
  22. 1.5. 有效期
  23. 证书有效期的时间段。本字段由”Not Before”和”Not After”两项组成,它们分别由UTC时间或一般的时间表示(在RFC2459中有详细的时间表示规则)。
  24. 1.6. 主体
  25. 证书拥有者的可识别名,这个字段必须是非空的,除非你在证书扩展中有别名。
  26. 1.7. 主体公钥信息
  27. 主体的公钥(以及算法标识符)。
  28. 1.8. 颁发者唯一标识符
  29. 标识符—证书颁发者的唯一标识符,仅在版本2和版本3中有要求,属于可选项。
  30. 1.9. 主体唯一标识符
  31. 证书拥有者的唯一标识符,仅在版本2和版本3中有要求,属于可选项。
  32. 2、X.509证书扩展部分
  33. 可选的标准和专用的扩展(仅在版本2和版本3中使用),扩展部分的元素都有这样的结构:
  34. Extension ::= SEQUENCE {
  35. extnID OBJECT IDENTIFIER,
  36. critical BOOLEAN DEFAULT FALSE,
  37. extnValue OCTET STRING }
  38. extnID:表示一个扩展元素的OID
  39. critical:表示这个扩展元素是否极重要
  40. extnValue:表示这个扩展元素的值,字符串类型。
  41. 扩展部分包括:
  42. 2.1. 发行者密钥标识符
  43. 证书所含密钥的唯一标识符,用来区分同一证书拥有者的多对密钥。
  44. 2.2. 密钥使用
  45. 一个比特串,指明(限定)证书的公钥可以完成的功能或服务,如:证书签名、数据加密等。
  46. 如果某一证书将 KeyUsage 扩展标记为“极重要”,而且设置为“keyCertSign”,则在 SSL 通信期间该证书出现时将被拒绝,因为该证书扩展表示相关私钥应只用于签写证书,而不应该用于 SSL。
  47. 2.3. CRL分布点
  48. 指明CRL的分布地点。
  49. 2.4. 私钥的使用期
  50. 指明证书中与公钥相联系的私钥的使用期限,它也有Not Before和Not After组成。若此项不存在时,公私钥的使用期是一样的。
  51. 2.5. 证书策略
  52. 由对象标识符和限定符组成,这些对象标识符说明证书的颁发和使用策略有关。
  53. 2.6. 策略映射
  54. 表明两个CA域之间的一个或多个策略对象标识符的等价关系,仅在CA证书里存在。
  55. 2.7. 主体别名
  56. 指出证书拥有者的别名,如电子邮件地址、IP地址等,别名是和DN绑定在一起的。
  57. 2.8. 颁发者别名
  58. 指出证书颁发者的别名,如电子邮件地址、IP地址等,但颁发者的DN必须出现在证书的颁发者字段。
  59. 2.9. 主体目录属性
  60. 指出证书拥有者的一系列属性。可以使用这一项来传递访问控制信息。
  61. 三、 X.509证书详细描述
  62. Certificate ::= SEQUENCE {
  63. tbsCertificate TBSCertificate, -- 证书主体
  64. signatureAlgorithm AlgorithmIdentifier, -- 证书签名算法标识
  65. signatureValue BIT STRING --证书签名值,是使用signatureAlgorithm部分指定的签名算法对tbsCertificate证书主题部分签名后的值.
  66. }
  67. TBSCertificate ::= SEQUENCE {
  68. version [0] EXPLICIT Version DEFAULT v1, -- 证书版本号
  69. serialNumber CertificateSerialNumber, -- 证书序列号,对同一CA所颁发的证书,序列号唯一标识证书
  70. signature AlgorithmIdentifier, --证书签名算法标识
  71. issuer Name, --证书发行者名称
  72. validity Validity, --证书有效期
  73. subject Name, --证书主体名称
  74. subjectPublicKeyInfo SubjectPublicKeyInfo,--证书公钥
  75. issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
  76. -- 证书发行者ID(可选),只在证书版本2、3中才有
  77. subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
  78. -- 证书主体ID(可选),只在证书版本2、3中才有
  79. extensions [3] EXPLICIT Extensions OPTIONAL
  80. -- 证书扩展段(可选),只在证书版本3中才有
  81. }
  82. Version ::= INTEGER { v1(0), v2(1), v3(2) }
  83. CertificateSerialNumber ::= INTEGER
  84. AlgorithmIdentifier ::= SEQUENCE {
  85. algorithm OBJECT IDENTIFIER,
  86. parameters ANY DEFINED BY algorithm OPTIONAL }
  87. parameters:
  88. Dss-Parms ::= SEQUENCE { -- parameters ,DSA(DSS)算法时的parameters,
  89. RSA算法没有此参数
  90. p INTEGER,
  91. q INTEGER,
  92. g INTEGER }
  93. signatureValue:
  94. Dss-Sig-Value ::= SEQUENCE { -- sha1DSA签名算法时,签名值
  95. r INTEGER,
  96. s INTEGER }
  97. Name ::= CHOICE {
  98. RDNSequence }
  99. RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  100. RelativeDistinguishedName ::=
  101. SET OF AttributeTypeAndValue
  102. AttributeTypeAndValue ::= SEQUENCE {
  103. type AttributeType,
  104. value AttributeValue }
  105. AttributeType ::= OBJECT IDENTIFIER
  106. AttributeValue ::= ANY DEFINED BY AttributeType
  107. Validity ::= SEQUENCE {
  108. notBefore Time, -- 证书有效期起始时间
  109. notAfter Time -- 证书有效期终止时间
  110. }
  111. Time ::= CHOICE {
  112. utcTime UTCTime,
  113. generalTime GeneralizedTime }
  114. UniqueIdentifier ::= BIT STRING
  115. SubjectPublicKeyInfo ::= SEQUENCE {
  116. algorithm AlgorithmIdentifier, -- 公钥算法
  117. subjectPublicKey BIT STRING -- 公钥值
  118. }
  119. subjectPublicKey:
  120. RSAPublicKey ::= SEQUENCE { -- RSA算法时的公钥值
  121. modulus INTEGER, -- n
  122. publicExponent INTEGER -- e -- }
  123. Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
  124. Extension ::= SEQUENCE {
  125. extnID OBJECT IDENTIFIER,
  126. critical BOOLEAN DEFAULT FALSE,
  127. extnValue OCTET STRING }
  128. */
  129. #include "head.h"
  130. #ifdef ENCRYPT_X509
  131. #ifdef LINUX_KERNEL_APP
  132. #include "x509.h"
  133. #include "base64.h"
  134. #include <linux/kernel.h>
  135. #include <linux/init.h>
  136. #include <linux/module.h>
  137. #include <linux/moduleparam.h>
  138. #include <linux/fs.h>
  139. #include <linux/sched.h>
  140. #include <linux/interrupt.h>
  141. #include <linux/kthread.h>
  142. #include <linux/delay.h>
  143. #include <linux/wait.h>
  144. #include <asm/uaccess.h>
  145. #include <asm/io.h>
  146. #include <asm/ioctls.h>
  147. #include <linux/syscalls.h>
  148. #include <termios.h>
  149. #else
  150. #include "head.h"
  151. #include "x509.h"
  152. #include "base64.h"
  153. #include <linux/fs.h>
  154. #include <linux/sched.h>
  155. #include <linux/wait.h>
  156. #include <asm/ioctls.h>
  157. #include <termios.h>
  158. #endif
  159. //#define X509_DEBUG
  160. #define V_ASN1_UTCTIME 23 //UTC时间类型
  161. #define V_ASN1_GENERALIZEDTIME 24 //非UTC时间类型
  162. #define SM2_PUBKEY_LENTH 68 //SM2公钥长度
  163. typedef struct{
  164. unsigned char type[128]; //类型
  165. unsigned char value[128]; //值
  166. int type_len; //类型长度
  167. int value_len; //值长度
  168. } TName;
  169. //证书有效期
  170. typedef struct{
  171. unsigned char notBefore[32]; //起始时间
  172. unsigned char notAfter[32]; //结束时间
  173. int notBefore_len; //起始时间长度
  174. int notAfter_len; //结束时间长度
  175. } Validity;
  176. //证书算法标示
  177. typedef struct {
  178. unsigned char algorithm[64]; //算法
  179. unsigned char parameters[64]; //参数
  180. int algorithm_len; //长度
  181. int parameters_len; //长度
  182. } AlgorithmIdentifier;
  183. //x509 V3扩展域
  184. typedef struct{
  185. unsigned char signature_a[64]; //签名算法
  186. unsigned char signature_v[256]; //签名值
  187. int signature_a_len; //长度
  188. int signature_v_len; //长度
  189. // unsigned char extnID[64];
  190. // unsigned char critical[64];
  191. // unsigned char extnValue[64];
  192. // int extnID_len;
  193. // int critical_len;
  194. // int extnValue_len;
  195. } Extension;
  196. //证书公钥
  197. typedef struct{
  198. AlgorithmIdentifier algorithm; //算法表示
  199. unsigned char subjectPublicKey[256];//公钥
  200. int subjectPublicKey_len; //公钥长度
  201. } SubjectPublicKeyInfo;
  202. // 证书主体
  203. typedef struct
  204. {
  205. unsigned int version; //证书版本号
  206. unsigned char serialNumber[64]; //证书序列号,对同一CA所颁发的证书,序列号唯一标识证书
  207. unsigned char signature[64]; //证书签名算法标识
  208. TName issuer[8]; //证书发行者名称
  209. Validity validity; // 证书有效期
  210. TName subject[8]; //证书主体名称
  211. SubjectPublicKeyInfo subjectPublicKeyInfo; //证书公钥
  212. // unsigned char issuerUniqueID [64];
  213. // unsigned char subjectUniqueID[64];
  214. Extension extensions; //证书扩展段
  215. int serialNumber_len; //长度
  216. int signature_len;
  217. int issuer_len;
  218. int subject_len;
  219. }TBSCertificate;
  220. //X.509证书详细描述
  221. struct Certificate
  222. {
  223. TBSCertificate tbsCertificate; //证书主体
  224. AlgorithmIdentifier signatureAlgorithm; //证书签名算法标识
  225. unsigned char *signatureValue; //证书签名值,是使用signatureAlgorithm部分指定的签名算法对tbsCertificate证书主题部分签名后的值
  226. };
  227. struct x509tm{
  228. uint32_t begin_time;
  229. uint32_t end_time;
  230. };
  231. //X.509证书全局变量
  232. static struct Certificate g_Certificate;
  233. //OID标示
  234. static char *OID[]=
  235. {
  236. "CN",
  237. "SP",
  238. "LO",
  239. "OU",
  240. "UN",
  241. "CM"
  242. };
  243. static struct x509tm g_x509tm[4];
  244. static int g_x509_cer_file_flag = 0;
  245. int x509_isvalid_time(int no, uint32_t locat_time)
  246. {
  247. struct timespec ts;
  248. struct rtc_time_t tm;
  249. char tmbuf[128];
  250. if((no > 3) || (no < 0))
  251. {
  252. rt_printf("%s: invalid no\n", __func__);
  253. return -1;
  254. }
  255. if(g_x509_cer_file_flag==0)
  256. {
  257. return 0;
  258. }
  259. if((g_x509tm[no].begin_time > locat_time) || (g_x509tm[no].end_time < locat_time))
  260. {
  261. rt_printf("%s: invalid time:\r\n", __func__);
  262. ts.tv_nsec = 0;
  263. ts.tv_sec = (long) g_x509tm[no].begin_time ;
  264. timespec_to_rtc(ts, &tm, 0);
  265. sprintf(tmbuf,"BEGIN TIME:20%02hu-%02hu-%02hu %02hu:%02hu:%02hu \r\n",tm.year,tm.month,tm.day,tm.hour,tm.min,tm.ms/1000);
  266. rt_printf(tmbuf);
  267. ts.tv_sec = (long) g_x509tm[no].end_time ;
  268. timespec_to_rtc(ts, &tm, 0);
  269. sprintf(tmbuf,"END TIME:20%02hu-%02hu-%02hu %02hu:%02hu:%02hu \r\n",tm.year,tm.month,tm.day,tm.hour,tm.min,tm.ms/1000);
  270. rt_printf(tmbuf);
  271. ts.tv_sec = (long)locat_time ;
  272. timespec_to_rtc(ts, &tm, 0);
  273. sprintf(tmbuf,"LOCAL TIME:20%02hu-%02hu-%02hu %02hu:%02hu:%02hu \r\n",tm.year,tm.month,tm.day,tm.hour,tm.min,tm.ms/1000);
  274. rt_printf(tmbuf);
  275. return -1;
  276. }
  277. return 0;
  278. }
  279. int x509_time_init(void)
  280. {
  281. int fd;
  282. int ret;
  283. memset(g_x509tm, 0, sizeof(g_x509tm));
  284. fd = sys_open(FILENAME_X509_TIME0, O_RDONLY, 0);
  285. if(fd < 0)
  286. {
  287. //rt_printf("%s:open %s error\n",__func__, FILENAME_X509_TIME0);
  288. }
  289. else
  290. {
  291. ret = sys_read(fd, (char *)&g_x509tm[0], 8);
  292. if(ret!=8)
  293. {
  294. rt_printf("%s:sys_read %s error\n",__func__, FILENAME_X509_TIME0);
  295. }
  296. sys_close(fd);
  297. g_x509_cer_file_flag = 1;
  298. }
  299. fd = sys_open(FILENAME_X509_TIME1, O_RDONLY, 0);
  300. if(fd < 0)
  301. {
  302. //rt_printf("%s:open %s error\n",__func__, FILENAME_X509_TIME1);
  303. }
  304. else
  305. {
  306. ret = sys_read(fd, (char *)&g_x509tm[1], 8);
  307. if(ret!=8)
  308. {
  309. rt_printf("%s:sys_read %s error\n",__func__, FILENAME_X509_TIME1);
  310. }
  311. sys_close(fd);
  312. g_x509_cer_file_flag = 1;
  313. }
  314. fd = sys_open(FILENAME_X509_TIME2, O_RDONLY, 0);
  315. if(fd < 0)
  316. {
  317. //rt_printf("%s:open %s error\n",__func__, FILENAME_X509_TIME2);
  318. }
  319. else
  320. {
  321. ret = sys_read(fd, (char *)&g_x509tm[2], 8);
  322. if(ret!=8)
  323. {
  324. rt_printf("%s:sys_read %s error\n",__func__, FILENAME_X509_TIME2);
  325. }
  326. sys_close(fd);
  327. g_x509_cer_file_flag = 1;
  328. }
  329. fd = sys_open(FILENAME_X509_TIME3, O_RDONLY, 0);
  330. if(fd < 0)
  331. {
  332. //rt_printf("%s:open %s error\n",__func__, FILENAME_X509_TIME3);
  333. }
  334. else
  335. {
  336. ret = sys_read(fd, (char *)&g_x509tm[3], 8);
  337. if(ret!=8)
  338. {
  339. rt_printf("%s:sys_read %s error\n",__func__, FILENAME_X509_TIME3);
  340. }
  341. sys_close(fd);
  342. g_x509_cer_file_flag = 1;
  343. }
  344. //x509_isvalid_time(0, g_x509tm[0].begin_time);
  345. //x509_isvalid_time(1, g_x509tm[1].begin_time);
  346. //x509_isvalid_time(2, g_x509tm[2].begin_time);
  347. //x509_isvalid_time(3, g_x509tm[3].begin_time);
  348. return 0;
  349. }
  350. /******************************************************************************
  351. 函数名称: from_s_to_d
  352. 函数版本: 01.01
  353. 创建作者:
  354. 创建日期: 2015-07-04
  355. 函数说明: 从字符串转整数.
  356. 参数说明:
  357. str:要转的字符串
  358. len:字符串长度
  359. 返回值: 整数值。
  360. 修改记录:
  361. */
  362. static unsigned int from_s_to_d(unsigned char *str, int len)
  363. {
  364. unsigned int value = 0;
  365. switch(len)
  366. {
  367. case 1:
  368. value = (unsigned int)str[0];
  369. break;
  370. case 2:
  371. value = (unsigned int)str[0] << 8;
  372. value |= (unsigned int)str[1] ;
  373. break;
  374. case 3:
  375. value = (unsigned int)str[0] << 16;
  376. value |= (unsigned int)str[1] << 8 ;
  377. value |= (unsigned int)str[2] ;
  378. break;
  379. case 4:
  380. value = (unsigned int)str[0] << 24;
  381. value |= (unsigned int)str[1] << 16;
  382. value |= (unsigned int)str[2] << 8;
  383. value |= (unsigned int)str[3] ;
  384. break;
  385. default:
  386. break;
  387. }
  388. return value;
  389. }
  390. /******************************************************************************
  391. 函数名称: get_oid_from_str
  392. 函数版本: 01.01
  393. 创建作者:
  394. 创建日期: 2015-07-04
  395. 函数说明: 从字符串得到OID.
  396. 参数说明:
  397. data:要转的字符串
  398. 返回值: OID值。
  399. 修改记录:
  400. */
  401. static char * get_oid_from_str(char *data)
  402. {
  403. if((data[0]==0x55) && (data[1]==0x04))
  404. {
  405. if(data[2]==0x06)
  406. {
  407. return OID[0];
  408. }
  409. else if(data[2]==0x0A)
  410. {
  411. return OID[3];
  412. }
  413. else if(data[2]==0x0B)
  414. {
  415. return OID[4];
  416. }
  417. else if(data[2]==0x03)
  418. {
  419. return OID[5];
  420. }
  421. else if(data[2]==0x07)
  422. {
  423. return OID[2];
  424. }
  425. else
  426. {
  427. return OID[1];
  428. }
  429. }
  430. return OID[0];
  431. }
  432. /******************************************************************************
  433. 函数名称: ASN1_GENERALIZEDTIME_check
  434. 函数版本: 01.01
  435. 创建作者:
  436. 创建日期: 2015-07-04
  437. 函数说明: 检查时间的合法性(非UTC时间).
  438. 参数说明:
  439. data:时间字符串
  440. data_len:字符串长度
  441. timetype:时间类型
  442. 返回值: 成功返回1,失败返回0。
  443. 修改记录:
  444. */
  445. static int ASN1_GENERALIZEDTIME_check(unsigned char *data, int data_len, int timetype)
  446. {
  447. static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
  448. static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
  449. char *a;
  450. int n, i, l, o;
  451. if (timetype != V_ASN1_GENERALIZEDTIME)
  452. return (0);
  453. l = data_len;
  454. a = (char *)data;
  455. o = 0;
  456. /*
  457. * GENERALIZEDTIME is similar to UTCTIME except the year is represented
  458. * as YYYY. This stuff treats everything as a two digit field so make
  459. * first two fields 00 to 99
  460. */
  461. if (l < 13)
  462. goto err;
  463. for (i = 0; i < 7; i++) {
  464. if ((i == 6) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
  465. i++;
  466. break;
  467. }
  468. if ((a[o] < '0') || (a[o] > '9'))
  469. goto err;
  470. n = a[o] - '0';
  471. if (++o > l)
  472. goto err;
  473. if ((a[o] < '0') || (a[o] > '9'))
  474. goto err;
  475. n = (n * 10) + a[o] - '0';
  476. if (++o > l)
  477. goto err;
  478. if ((n < min[i]) || (n > max[i]))
  479. goto err;
  480. }
  481. /*
  482. * Optional fractional seconds: decimal point followed by one or more
  483. * digits.
  484. */
  485. if (a[o] == '.') {
  486. if (++o > l)
  487. goto err;
  488. i = o;
  489. while ((a[o] >= '0') && (a[o] <= '9') && (o <= l))
  490. o++;
  491. /* Must have at least one digit after decimal point */
  492. if (i == o)
  493. goto err;
  494. }
  495. if (a[o] == 'Z')
  496. o++;
  497. else if ((a[o] == '+') || (a[o] == '-')) {
  498. o++;
  499. if (o + 4 > l)
  500. goto err;
  501. for (i = 7; i < 9; i++) {
  502. if ((a[o] < '0') || (a[o] > '9'))
  503. goto err;
  504. n = a[o] - '0';
  505. o++;
  506. if ((a[o] < '0') || (a[o] > '9'))
  507. goto err;
  508. n = (n * 10) + a[o] - '0';
  509. if ((n < min[i]) || (n > max[i]))
  510. goto err;
  511. o++;
  512. }
  513. } else {
  514. /* Missing time zone information. */
  515. goto err;
  516. }
  517. return (o == l);
  518. err:
  519. return (0);
  520. }
  521. /******************************************************************************
  522. 函数名称: ASN1_UTCTIME_check
  523. 函数版本: 01.01
  524. 创建作者:
  525. 创建日期: 2015-07-04
  526. 函数说明: 检查时间的合法性(UTC时间).
  527. 参数说明:
  528. data:时间字符串
  529. data_len:字符串长度
  530. timetype:时间类型
  531. 返回值: 成功返回1,失败返回0。
  532. 修改记录:
  533. */
  534. static int ASN1_UTCTIME_check(unsigned char *data, int data_len, int timetype)
  535. {
  536. static const int min[8] = { 0, 1, 1, 0, 0, 0, 0, 0 };
  537. static const int max[8] = { 99, 12, 31, 23, 59, 59, 12, 59 };
  538. char *a;
  539. int n, i, l, o;
  540. if (timetype != V_ASN1_UTCTIME)
  541. return (0);
  542. l = data_len;
  543. a = (char *)data;
  544. o = 0;
  545. if (l < 11)
  546. goto err;
  547. for (i = 0; i < 6; i++) {
  548. if ((i == 5) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
  549. i++;
  550. break;
  551. }
  552. if ((a[o] < '0') || (a[o] > '9'))
  553. goto err;
  554. n = a[o] - '0';
  555. if (++o > l)
  556. goto err;
  557. if ((a[o] < '0') || (a[o] > '9'))
  558. goto err;
  559. n = (n * 10) + a[o] - '0';
  560. if (++o > l)
  561. goto err;
  562. if ((n < min[i]) || (n > max[i]))
  563. goto err;
  564. }
  565. if (a[o] == 'Z')
  566. o++;
  567. else if ((a[o] == '+') || (a[o] == '-')) {
  568. o++;
  569. if (o + 4 > l)
  570. goto err;
  571. for (i = 6; i < 8; i++) {
  572. if ((a[o] < '0') || (a[o] > '9'))
  573. goto err;
  574. n = a[o] - '0';
  575. o++;
  576. if ((a[o] < '0') || (a[o] > '9'))
  577. goto err;
  578. n = (n * 10) + a[o] - '0';
  579. if ((n < min[i]) || (n > max[i]))
  580. goto err;
  581. o++;
  582. }
  583. }
  584. return (o == l);
  585. err:
  586. return (0);
  587. }
  588. /******************************************************************************
  589. 函数名称: x509_get_one_blk_data
  590. 函数版本: 01.01
  591. 创建作者:
  592. 创建日期: 2015-07-04
  593. 函数说明: 获取一个数据块.
  594. 参数说明:
  595. src_data:源数据
  596. data_len:数据内容的长度
  597. 返回值: 数据块内容的首地址。
  598. 修改记录:
  599. */
  600. static unsigned char *x509_get_one_blk_data(unsigned char *src_data, unsigned int *data_len)
  601. {
  602. unsigned char *p=src_data;
  603. int pos = 0;
  604. unsigned int total_len = 0;
  605. unsigned char byte_d[8]={0};
  606. int byte_cnt = 0;
  607. int i = 0;
  608. //多字节的情况
  609. if(p[1] & 0x80)
  610. {
  611. byte_cnt= (int)(p[1] & 0x7F);
  612. for(i=0;(i<4) && (i<byte_cnt); i++)
  613. {
  614. byte_d[i]=p[2+i];
  615. }
  616. if(byte_cnt) //长度固定的情况
  617. {
  618. total_len=from_s_to_d(byte_d, byte_cnt);
  619. pos=2+ byte_cnt;
  620. }
  621. else
  622. {
  623. //长度不固定的情况
  624. pos = 2;
  625. }
  626. }
  627. else //单字节的情况
  628. {
  629. byte_cnt=(int)(p[1] & 0x7F);
  630. if(byte_cnt) //长度固定的情况
  631. {
  632. total_len=from_s_to_d(&p[1], 1);
  633. pos=2;
  634. }
  635. else
  636. {
  637. //长度不固定的情况
  638. pos = 2;
  639. }
  640. }
  641. *data_len = total_len;
  642. return (unsigned char *)(p+pos);
  643. }
  644. /******************************************************************************
  645. 函数名称: x509_decode
  646. 函数版本: 01.01
  647. 创建作者:
  648. 创建日期: 2015-07-04
  649. 函数说明: X509证书解码.
  650. 参数说明:
  651. data:证书内容
  652. data_len:证书长度
  653. 返回值: 成功返回0,失败返回-1
  654. 修改记录:
  655. */
  656. static int x509_decode(unsigned char *data, int data_len)
  657. {
  658. unsigned char *p=data;
  659. unsigned char *ptr_begin=data;
  660. unsigned char *ptr_end;
  661. int i = 0;
  662. //int j = 0;
  663. unsigned int total_len = 0;
  664. unsigned int len_tmp = 0;
  665. //Certificate ::= SEQUENCE
  666. if(p[0]!=0x30)
  667. {
  668. rt_printf("%s:head error\n",__func__);
  669. return -1;
  670. }
  671. //Certificate
  672. p = x509_get_one_blk_data(p, &total_len);
  673. //tbsCertificate 证书主体
  674. p = x509_get_one_blk_data(p, &len_tmp);
  675. ptr_begin = p;
  676. //version 证书版本号
  677. p = x509_get_one_blk_data(p, &len_tmp);
  678. if(ptr_begin[0]!=0xA0)
  679. {
  680. rt_printf("%s:not version type\n",__func__);
  681. return -1;
  682. }
  683. p = x509_get_one_blk_data(p, &len_tmp);
  684. //版本号
  685. g_Certificate.tbsCertificate.version = from_s_to_d(p, len_tmp);
  686. if(g_Certificate.tbsCertificate.version > 2)
  687. {
  688. rt_printf("%s:not valid version\n",__func__);
  689. return -1;
  690. }
  691. #ifdef X509_DEBUG
  692. rt_printf("Version:\n%d\n", g_Certificate.tbsCertificate.version);
  693. #endif
  694. p=&p[len_tmp];
  695. //serialNumber 证书序列号,对同一CA所颁发的证书,序列号唯一标识证书
  696. p = x509_get_one_blk_data(p, &len_tmp);
  697. //序列号
  698. g_Certificate.tbsCertificate.serialNumber_len =len_tmp;
  699. memcpy(g_Certificate.tbsCertificate.serialNumber, p, len_tmp);
  700. #ifdef X509_DEBUG
  701. rt_printf("serialNumber:\n");
  702. for(i=0;i<g_Certificate.tbsCertificate.serialNumber_len;i++)
  703. {
  704. rt_printf("%02x ", g_Certificate.tbsCertificate.serialNumber[i]);
  705. }
  706. rt_printf("\n");
  707. #endif
  708. p=&p[len_tmp];
  709. //signature 证书签名算法标识
  710. p = x509_get_one_blk_data(p, &len_tmp);
  711. ptr_end = &p[len_tmp]; //下一个数据块的内容指针
  712. p = x509_get_one_blk_data(p, &len_tmp);
  713. g_Certificate.tbsCertificate.signature_len =len_tmp;
  714. memcpy(g_Certificate.tbsCertificate.signature, p, len_tmp);
  715. #if 0
  716. rt_printf("signature:\n");
  717. for(i=0;i<g_Certificate.tbsCertificate.signature_len;i++)
  718. {
  719. rt_printf("%02x ",g_Certificate.tbsCertificate.signature[i]);
  720. }
  721. rt_printf("\n");
  722. #endif
  723. p = ptr_end;
  724. //issuer 证书发行者名称
  725. // Name ::= CHOICE {
  726. // RDNSequence }
  727. p = x509_get_one_blk_data(p, &len_tmp);
  728. ptr_end = &p[len_tmp]; //下一个数据块的内容指针
  729. #ifdef X509_DEBUG
  730. rt_printf("issuer:\n");
  731. #endif
  732. for(i=0; (i<6) && (ptr_end > p); i++)
  733. {
  734. //RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  735. //RelativeDistinguishedName ::=
  736. // SET OF AttributeTypeAndValue
  737. p = x509_get_one_blk_data(p, &len_tmp);
  738. //AttributeTypeAndValue ::= SEQUENCE {
  739. // type AttributeType,
  740. // value AttributeValue }
  741. p = x509_get_one_blk_data(p, &len_tmp);
  742. // type AttributeType,
  743. p = x509_get_one_blk_data(p, &len_tmp);
  744. memcpy(g_Certificate.tbsCertificate.issuer[i].type, p, len_tmp);
  745. g_Certificate.tbsCertificate.issuer[i].type_len = len_tmp;
  746. p = &p[len_tmp];
  747. //value AttributeValue
  748. p = x509_get_one_blk_data(p, &len_tmp);
  749. memcpy(g_Certificate.tbsCertificate.issuer[i].value, p, len_tmp);
  750. g_Certificate.tbsCertificate.issuer[i].value_len = len_tmp;
  751. p = &p[len_tmp];
  752. #if 0
  753. for(j=0;j<g_Certificate.tbsCertificate.issuer[i].type_len;j++)
  754. {
  755. rt_printf("%02x ", g_Certificate.tbsCertificate.issuer[i].type[j]);
  756. }
  757. rt_printf("\n");
  758. for(j=0;j<g_Certificate.tbsCertificate.issuer[i].value_len;j++)
  759. {
  760. rt_printf("%02x ", g_Certificate.tbsCertificate.issuer[i].value[j]);
  761. }
  762. rt_printf("\n\n");
  763. #else
  764. #ifdef X509_DEBUG
  765. rt_printf("%s:", get_oid_from_str(g_Certificate.tbsCertificate.issuer[i].type));
  766. rt_printf("%s\n", g_Certificate.tbsCertificate.issuer[i].value);
  767. #endif
  768. #endif
  769. g_Certificate.tbsCertificate.issuer_len++;
  770. }
  771. p=ptr_end;
  772. // validity Validity, --证书有效期
  773. //notBefore
  774. p = x509_get_one_blk_data(p, &len_tmp);
  775. ptr_end = &p[len_tmp]; //下一个数据块的内容指针
  776. //检查证书有效期起始时间的合法性
  777. if(!ASN1_UTCTIME_check(p+2, (int)p[1], (int)p[0]))
  778. {
  779. if(!ASN1_GENERALIZEDTIME_check(p+2, (int)p[1], (int)p[0]))
  780. {
  781. rt_printf("%s:notBefore time error\n",__func__);
  782. return -1;
  783. }
  784. }
  785. memcpy(g_Certificate.tbsCertificate.validity.notBefore, p+2, (int)p[1]-1);
  786. g_Certificate.tbsCertificate.validity.notBefore_len = (int)p[1]-1;
  787. //notAfter
  788. p=&p[g_Certificate.tbsCertificate.validity.notBefore_len+2+1];
  789. //检查证书有效期结束时间的合法性
  790. if(!ASN1_UTCTIME_check(p+2, (int)p[1], (int)p[0]))
  791. {
  792. if(!ASN1_GENERALIZEDTIME_check(p+2, (int)p[1], (int)p[0]))
  793. {
  794. rt_printf("%s:notBefore time error\n",__func__);
  795. return -1;
  796. }
  797. }
  798. memcpy(g_Certificate.tbsCertificate.validity.notAfter, p+2, (int)p[1]-1);
  799. g_Certificate.tbsCertificate.validity.notAfter_len = (int)p[1]-1;
  800. p = ptr_end;
  801. #ifdef X509_DEBUG
  802. rt_printf("Start Time(%d):\r\n", g_Certificate.tbsCertificate.validity.notBefore_len);
  803. {
  804. char *pp = g_Certificate.tbsCertificate.validity.notBefore;
  805. rt_printf("20%c%c-%c%c-%c%c %c%c:%c%c:%c%c\n", pp[0], pp[1], pp[2], pp[3],pp[4], pp[5], pp[6], pp[7], pp[8], pp[9],pp[10], pp[11]);
  806. }
  807. rt_printf("End Time(%d):\r\n", g_Certificate.tbsCertificate.validity.notAfter_len);
  808. {
  809. char *pp = g_Certificate.tbsCertificate.validity.notAfter;
  810. rt_printf("20%c%c-%c%c-%c%c %c%c:%c%c:%c%c\n", pp[0], pp[1], pp[2], pp[3],pp[4], pp[5], pp[6], pp[7], pp[8], pp[9],pp[10], pp[11]);
  811. }
  812. #endif
  813. #ifdef X509_DEBUG
  814. rt_printf("subject: \r\n");
  815. #endif
  816. //subject 证书主体名称
  817. // Name ::= CHOICE {
  818. // RDNSequence }
  819. p = x509_get_one_blk_data(p, &len_tmp);
  820. ptr_end = &p[len_tmp]; //下一个数据块的内容指针
  821. for(i=0; (i<6) && (ptr_end > p); i++)
  822. {
  823. //RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  824. //RelativeDistinguishedName ::=
  825. // SET OF AttributeTypeAndValue
  826. p = x509_get_one_blk_data(p, &len_tmp);
  827. //AttributeTypeAndValue ::= SEQUENCE {
  828. // type AttributeType,
  829. // value AttributeValue }
  830. p = x509_get_one_blk_data(p, &len_tmp);
  831. // type AttributeType,
  832. p = x509_get_one_blk_data(p, &len_tmp);
  833. memcpy(g_Certificate.tbsCertificate.subject[i].type, p, len_tmp);
  834. g_Certificate.tbsCertificate.subject[i].type_len = len_tmp;
  835. p = &p[len_tmp];
  836. //value AttributeValue
  837. p = x509_get_one_blk_data(p, &len_tmp);
  838. memcpy(g_Certificate.tbsCertificate.subject[i].value, p, len_tmp);
  839. g_Certificate.tbsCertificate.subject[i].value_len = len_tmp;
  840. p = &p[len_tmp];
  841. #if 0
  842. for(j=0;j<g_Certificate.tbsCertificate.subject[i].type_len;j++)
  843. {
  844. rt_printf("%02x ", g_Certificate.tbsCertificate.subject[i].type[j]);
  845. }
  846. rt_printf("\n");
  847. for(j=0;j<g_Certificate.tbsCertificate.subject[i].value_len;j++)
  848. {
  849. rt_printf("%02x ", g_Certificate.tbsCertificate.subject[i].value[j]);
  850. }
  851. rt_printf("\n\n");
  852. #else
  853. #ifdef X509_DEBUG
  854. rt_printf("%s:", get_oid_from_str(g_Certificate.tbsCertificate.subject[i].type));
  855. rt_printf("%s\n", g_Certificate.tbsCertificate.subject[i].value);
  856. #endif
  857. #endif
  858. g_Certificate.tbsCertificate.subject_len++;
  859. }
  860. p=ptr_end;
  861. // subjectPublicKeyInfo SubjectPublicKeyInfo,--证书公钥
  862. p = x509_get_one_blk_data(p, &len_tmp);
  863. ptr_end = &p[len_tmp]; //下一个数据块的内容指针
  864. // algorithm AlgorithmIdentifier, -- 公钥算法
  865. p = x509_get_one_blk_data(p, &len_tmp);
  866. ptr_begin = p;
  867. p = x509_get_one_blk_data(ptr_begin, &len_tmp);
  868. memcpy(g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm, p, len_tmp);
  869. g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm_len = len_tmp;
  870. p=&p[len_tmp];
  871. #if 0
  872. rt_printf("algorithm: \r\n");
  873. for(i=0;i<g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm_len;i++)
  874. {
  875. rt_printf("%02x ", g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm[i]);
  876. }
  877. rt_printf("\n\n");
  878. #endif
  879. //parameters
  880. p = x509_get_one_blk_data(p, &len_tmp);
  881. memcpy(g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.parameters, p, len_tmp);
  882. g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.parameters_len = len_tmp;
  883. p=&p[len_tmp];
  884. #if 0
  885. rt_printf("parameters: \r\n");
  886. for(i=0;i<g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.parameters_len;i++)
  887. {
  888. rt_printf("%02x ", g_Certificate.tbsCertificate.subjectPublicKeyInfo.algorithm.parameters[i]);
  889. }
  890. rt_printf("\n\n");
  891. #endif
  892. //subjectPublicKey BIT STRING -- 公钥值
  893. p = x509_get_one_blk_data(p, &len_tmp);
  894. memcpy(g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey, p, len_tmp);
  895. g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len = len_tmp;
  896. p=ptr_end;
  897. #ifdef X509_DEBUG
  898. rt_printf("subjectPublicKey: \r\n");
  899. for(i=0;i<g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len;i++)
  900. {
  901. rt_printf("%02x ", g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey[i]);
  902. }
  903. rt_printf("\n\n");
  904. #endif
  905. // extensions [3] EXPLICIT Extensions OPTIONAL
  906. // -- 证书扩展段(可选),只在证书版本3中才有
  907. //扩展域只解释签名算法和签名值(最后两个域)
  908. //已经到数据末端,返回
  909. if((p - data) <= 0)
  910. {
  911. return 0;
  912. }
  913. //非扩展域,返回
  914. if(p[0]!=0xA3)
  915. {
  916. rt_printf("%s:no extensions(%d)\n",__func__, (int)p[0]);
  917. return 0;
  918. }
  919. //Extension ::= SEQUENCE
  920. p = x509_get_one_blk_data(p, &len_tmp);
  921. p = &p[len_tmp];
  922. p = x509_get_one_blk_data(p, &len_tmp);
  923. ptr_begin = &p[len_tmp];
  924. p = x509_get_one_blk_data(p, &len_tmp);
  925. memcpy(g_Certificate.tbsCertificate.extensions.signature_a, p, len_tmp);
  926. g_Certificate.tbsCertificate.extensions.signature_a_len = len_tmp;
  927. ptr_end=data+data_len;
  928. memcpy(g_Certificate.tbsCertificate.extensions.signature_v, ptr_begin, (int)(ptr_end-ptr_begin));
  929. g_Certificate.tbsCertificate.extensions.signature_v_len = (int)(ptr_end-ptr_begin);
  930. #ifdef X509_DEBUG
  931. rt_printf("Extension signature:\n");
  932. for(i=0;i<g_Certificate.tbsCertificate.extensions.signature_a_len;i++)
  933. {
  934. rt_printf("%02x ", g_Certificate.tbsCertificate.extensions.signature_a[i]);
  935. }
  936. rt_printf("\n\n");
  937. rt_printf("Extension signature Value:\n");
  938. for(i=0;i<g_Certificate.tbsCertificate.extensions.signature_v_len;i++)
  939. {
  940. rt_printf("%02x ", g_Certificate.tbsCertificate.extensions.signature_v[i]);
  941. }
  942. rt_printf("\n\n");
  943. #endif
  944. return 0;
  945. }
  946. /******************************************************************************
  947. 函数名称: x509_cer_to_sm2keybin
  948. 函数版本: 01.01
  949. 创建作者:
  950. 创建日期: 2015-07-04
  951. 函数说明: 从cer文件(二进制格式)解码生成sm2keybin 文件.
  952. 参数说明:
  953. srcfile:cer文件源文件(base64格式)
  954. f_cer:cer文件(二进制格式)
  955. f_sm2keybin:sm2keybin文件
  956. 返回值: 成功返回0,失败返回-1
  957. 修改记录:
  958. */
  959. static int x509_cer_to_sm2keybin(char *srcfile, char *f_cer, char * f_sm2keybin)
  960. {
  961. struct stat s;
  962. char *file_data;
  963. int fd ;
  964. int ret;
  965. memset(&g_Certificate, 0, sizeof(g_Certificate));
  966. //获取文件属性
  967. if(sys_newstat(f_cer,&s))
  968. {
  969. rt_printf("%s:sys_newstat error\n",__func__);
  970. return -1;
  971. }
  972. //分配内存
  973. file_data = rt_malloc(s.st_size);
  974. if(!file_data)
  975. {
  976. rt_printf("%s:rt_malloc error\n",__func__);
  977. return -1;
  978. }
  979. //打开文件
  980. fd = sys_open(f_cer, O_RDONLY, 0);
  981. if(fd < 0)
  982. {
  983. rt_printf("%s:sys_open %s error\n",__func__ , f_cer);
  984. rt_free(file_data);
  985. return -1;
  986. }
  987. //读取整个文件内容
  988. ret = sys_read(fd, file_data, s.st_size);
  989. if(ret!=s.st_size)
  990. {
  991. rt_printf("%s:sys_read error\n",__func__);
  992. sys_close(fd);
  993. rt_free(file_data);
  994. return -1;
  995. }
  996. sys_close(fd);
  997. ret=x509_decode(file_data, (int)s.st_size);
  998. if(ret==0)
  999. {
  1000. rt_printf("%s:%s x509_decode OK\n",__func__, srcfile);
  1001. }
  1002. else
  1003. {
  1004. rt_printf("%s:%s x509_decode error!\n",__func__, srcfile);
  1005. rt_free(file_data);
  1006. return -1;
  1007. }
  1008. rt_free(file_data);
  1009. //大于68字节不生成文件
  1010. if(g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len > SM2_PUBKEY_LENTH)
  1011. {
  1012. rt_printf("%s:PublicKey too big (%d)t\n",__func__, g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len);
  1013. return -1;
  1014. }
  1015. fd = sys_open(f_sm2keybin, O_CREAT|O_RDWR | O_TRUNC|O_SYNC, 0777);
  1016. if(fd < 0)
  1017. {
  1018. rt_printf("%s:creat file %s error\n",__func__, f_sm2keybin);
  1019. return -1;
  1020. }
  1021. if(g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len < SM2_PUBKEY_LENTH)
  1022. {
  1023. int fillzero = SM2_PUBKEY_LENTH - g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len;
  1024. //分配内存
  1025. file_data = rt_malloc(fillzero);
  1026. if(!file_data)
  1027. {
  1028. rt_printf("%s:rt_malloc error fillzero\n",__func__);
  1029. sys_close(fd);
  1030. return -1;
  1031. }
  1032. memset(file_data, 0, fillzero);
  1033. //填充0
  1034. ret = sys_write(fd, file_data, fillzero);
  1035. rt_free(file_data);//sunxi 20180719 added
  1036. if(ret != fillzero)
  1037. {
  1038. rt_printf("%s:sys_write error fillzero\n",__func__);
  1039. sys_close(fd);
  1040. return -1;
  1041. }
  1042. ret = sys_write(fd, g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey, g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len);
  1043. if(ret != g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len)
  1044. {
  1045. rt_printf("%s:sys_write error subjectPublicKey\n",__func__);
  1046. sys_close(fd);
  1047. return -1;
  1048. }
  1049. }
  1050. else
  1051. {
  1052. ret = sys_write(fd, g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey, g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len);
  1053. if(ret != g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len)
  1054. {
  1055. rt_printf("%s:sys_write error subjectPublicKey\n",__func__);
  1056. sys_close(fd);
  1057. return -1;
  1058. }
  1059. }
  1060. sys_close(fd);
  1061. return 0;
  1062. }
  1063. /******************************************************************************
  1064. 函数名称: write_data_to_file
  1065. 函数版本: 01.01
  1066. 创建作者:
  1067. 创建日期: 2015-07-04
  1068. 函数说明: 写数据到文件中.
  1069. 参数说明:
  1070. filename:文件名
  1071. data:要写的数据
  1072. len: 数据长度
  1073. 返回值: 成功返回0,失败返回-1
  1074. 修改记录:
  1075. */
  1076. static int write_data_to_file(char *filename, char *data, int len)
  1077. {
  1078. int fd;
  1079. int ret = 0;
  1080. fd = sys_open(filename, O_CREAT|O_RDWR | O_TRUNC|O_SYNC, 0777);
  1081. if(fd < 0)
  1082. {
  1083. rt_printf("%s:creat file %s error\n",__func__, filename);
  1084. return -1;
  1085. }
  1086. ret = sys_write(fd, data, len);
  1087. if(ret != len)
  1088. {
  1089. rt_printf("%s:creat file %s error\n",__func__, filename);
  1090. return -1;
  1091. }
  1092. sys_close(fd);
  1093. return 0;
  1094. }
  1095. /******************************************************************************
  1096. 函数名称: x509_parse
  1097. 函数版本: 01.01
  1098. 创建作者:
  1099. 创建日期: 2015-07-04
  1100. 函数说明: 解码x509证书并打印内容.
  1101. 参数说明:
  1102. srcfile:cer文件源文件(base64格式)
  1103. filename:cer文件(二进制格式)
  1104. 返回值: 成功返回0,失败返回-1
  1105. 修改记录:
  1106. */
  1107. static int x509_parse(char *srcfile, char *filename)
  1108. {
  1109. struct stat s;
  1110. char *file_data;
  1111. int fd ;
  1112. int ret;
  1113. int i = 0;
  1114. char *pp;
  1115. memset(&g_Certificate, 0, sizeof(g_Certificate));
  1116. //获取文件属性
  1117. if(sys_newstat(filename,&s))
  1118. {
  1119. rt_printf("%s:sys_newstat error\n",__func__);
  1120. return -1;
  1121. }
  1122. //分配内存
  1123. file_data = rt_malloc(s.st_size);
  1124. if(!file_data)
  1125. {
  1126. rt_printf("%s:rt_malloc error\n",__func__);
  1127. return -1;
  1128. }
  1129. //打开文件
  1130. fd = sys_open(filename, O_RDONLY, 0);
  1131. if(fd < 0)
  1132. {
  1133. rt_printf("%s:sys_open %s error\n",__func__ , filename);
  1134. rt_free(file_data);
  1135. return -1;
  1136. }
  1137. //读取整个文件内容
  1138. ret = sys_read(fd, file_data, s.st_size);
  1139. if(ret!=s.st_size)
  1140. {
  1141. rt_printf("%s:sys_read error\n",__func__);
  1142. sys_close(fd);
  1143. rt_free(file_data);
  1144. return -1;
  1145. }
  1146. sys_close(fd);
  1147. ret=x509_decode(file_data, (int)s.st_size);
  1148. if(ret==0)
  1149. {
  1150. //rt_printf("%s:x509_decode OK\n",__func__);
  1151. }
  1152. else
  1153. {
  1154. rt_printf("%s:x509_decode %s error!\n",__func__, filename);
  1155. rt_free(file_data);
  1156. return -1;
  1157. }
  1158. rt_free(file_data);
  1159. rt_printf("文件名:%s\n", srcfile);
  1160. rt_printf("版本:\n");
  1161. rt_printf("%d\n", g_Certificate.tbsCertificate.version);
  1162. rt_printf("证书序列号:\n");
  1163. for(i=0;i<g_Certificate.tbsCertificate.serialNumber_len;i++)
  1164. {
  1165. rt_printf("%02x ", g_Certificate.tbsCertificate.serialNumber[i]);
  1166. }
  1167. rt_printf("\n");
  1168. rt_printf("颁发者信息:\n");
  1169. for(i=0;i<g_Certificate.tbsCertificate.issuer_len;i++)
  1170. {
  1171. rt_printf("%s:", get_oid_from_str(g_Certificate.tbsCertificate.issuer[i].type));
  1172. rt_printf("%s\n", g_Certificate.tbsCertificate.issuer[i].value);
  1173. }
  1174. rt_printf("有效期:\n");
  1175. rt_printf("起始时间:");
  1176. pp = g_Certificate.tbsCertificate.validity.notBefore;
  1177. rt_printf("20%c%c-%c%c-%c%c %c%c:%c%c:%c%c\n", pp[0], pp[1], pp[2], pp[3],pp[4], pp[5], pp[6], pp[7], pp[8], pp[9],pp[10], pp[11]);
  1178. rt_printf("结束时间:");
  1179. pp = g_Certificate.tbsCertificate.validity.notAfter;
  1180. rt_printf("20%c%c-%c%c-%c%c %c%c:%c%c:%c%c\n", pp[0], pp[1], pp[2], pp[3],pp[4], pp[5], pp[6], pp[7], pp[8], pp[9],pp[10], pp[11]);
  1181. rt_printf("主题:\n");
  1182. for(i=0;i<g_Certificate.tbsCertificate.subject_len;i++)
  1183. {
  1184. rt_printf("%s:", get_oid_from_str(g_Certificate.tbsCertificate.subject[i].type));
  1185. rt_printf("%s\n", g_Certificate.tbsCertificate.subject[i].value);
  1186. }
  1187. rt_printf("公钥:\n");
  1188. //for(i=0;i<g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len;i++)
  1189. //{
  1190. // rt_printf("%02x ", g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey[i]);
  1191. //}
  1192. print_msg("", g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey, g_Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey_len);
  1193. //rt_printf("\n");
  1194. rt_printf("签名算法:\n");
  1195. //for(i=0;i<g_Certificate.tbsCertificate.signature_len;i++)
  1196. //{
  1197. // rt_printf("%02x ",g_Certificate.tbsCertificate.signature[i]);
  1198. //}
  1199. print_msg("", g_Certificate.tbsCertificate.signature, g_Certificate.tbsCertificate.signature_len);
  1200. //rt_printf("\n");
  1201. rt_printf("签名值:\n");
  1202. //for(i=0;i<g_Certificate.tbsCertificate.extensions.signature_v_len;i++)
  1203. //{
  1204. // rt_printf("%02x ", g_Certificate.tbsCertificate.extensions.signature_v[i]);
  1205. //}
  1206. print_msg("", g_Certificate.tbsCertificate.extensions.signature_v, g_Certificate.tbsCertificate.extensions.signature_v_len);
  1207. rt_printf("\n\n");
  1208. return 0;
  1209. }
  1210. /******************************************************************************
  1211. 函数名称: x509_print
  1212. 函数版本: 01.01
  1213. 创建作者:
  1214. 创建日期: 2015-07-04
  1215. 函数说明: 打印证书内容.
  1216. 参数说明:
  1217. base64file:cer文件源文件(base64格式)
  1218. binfile:cer文件(二进制格式)
  1219. 返回值: 成功返回0,失败返回-1
  1220. 修改记录:
  1221. */
  1222. static int x509_print(char * base64file, char * binfile)
  1223. {
  1224. int ret;
  1225. ret = base64file_to_binfile(base64file, binfile);
  1226. if(ret!=0)
  1227. {
  1228. rt_printf("%s: convert %s to bin error\n",__func__ , base64file);
  1229. return -1;
  1230. }
  1231. x509_parse(base64file, binfile);
  1232. return 0;
  1233. }
  1234. int x509_show_all(void)
  1235. {
  1236. x509_print(FILENAME_X509_CER_0, FILENAME_X509_CER_TMP_0);
  1237. x509_print(FILENAME_X509_CER_1, FILENAME_X509_CER_TMP_1);
  1238. x509_print(FILENAME_X509_CER_2, FILENAME_X509_CER_TMP_2);
  1239. x509_print(FILENAME_X509_CER_3, FILENAME_X509_CER_TMP_3);
  1240. return 0;
  1241. }
  1242. static int x509_writetime_to_file(char *filename, char * time_begin, int time_begin_len, char * time_end, int time_end_len)
  1243. {
  1244. struct rtc_time_t rt;
  1245. struct timespec ts;
  1246. char c_tm[32];
  1247. int i = 0;
  1248. int fd;
  1249. int ret = 0;
  1250. fd = sys_open(filename, O_CREAT|O_RDWR | O_TRUNC|O_SYNC, 0777);
  1251. if(fd < 0)
  1252. {
  1253. rt_printf("%s:creat file %s error\n",__func__, filename);
  1254. return -1;
  1255. }
  1256. for(i=0;i<time_begin_len;i++)
  1257. {
  1258. c_tm[i] = time_begin[i] - '0';
  1259. }
  1260. rt.year = (unsigned short)c_tm[0]*10+ (unsigned short)c_tm[1] ;
  1261. rt.month = (unsigned char)c_tm[2]*10+ (unsigned char)c_tm[3];
  1262. rt.day = (unsigned char)c_tm[4]*10+ (unsigned char)c_tm[5];
  1263. rt.hour= (unsigned char)c_tm[6]*10+ (unsigned char)c_tm[7];
  1264. rt.min= (unsigned char)c_tm[8]*10+ (unsigned char)c_tm[9];
  1265. rt.ms= (unsigned short)c_tm[10]*10+ (unsigned short)c_tm[11] ;
  1266. rt.ms = rt.ms *1000;
  1267. rtc_to_timespec(&rt, &ts);
  1268. ret=sys_write(fd, (char *)&ts.tv_sec, sizeof(ts.tv_sec));
  1269. if(ret != sizeof(ts.tv_sec))
  1270. {
  1271. rt_printf("%s:sys_write error\n",__func__);
  1272. sys_close(fd);
  1273. return -1;
  1274. }
  1275. for(i=0;i<time_end_len;i++)
  1276. {
  1277. c_tm[i] = time_end[i] - '0';
  1278. }
  1279. rt.year = (unsigned short)c_tm[0]*10+ (unsigned short)c_tm[1] ;
  1280. rt.month = (unsigned char)c_tm[2]*10+ (unsigned char)c_tm[3];
  1281. rt.day = (unsigned char)c_tm[4]*10+ (unsigned char)c_tm[5];
  1282. rt.hour= (unsigned char)c_tm[6]*10+ (unsigned char)c_tm[7];
  1283. rt.min= (unsigned char)c_tm[8]*10+ (unsigned char)c_tm[9];
  1284. rt.ms= (unsigned short)c_tm[10]*10+ (unsigned short)c_tm[11] ;
  1285. rt.ms = rt.ms *1000;
  1286. rtc_to_timespec(&rt, &ts);
  1287. ret=sys_write(fd, (char *)&ts.tv_sec, sizeof(ts.tv_sec));
  1288. if(ret != sizeof(ts.tv_sec))
  1289. {
  1290. rt_printf("%s:sys_write error\n",__func__);
  1291. sys_close(fd);
  1292. return -1;
  1293. }
  1294. sys_close(fd);
  1295. return 0;
  1296. }
  1297. /******************************************************************************
  1298. 函数名称: x509_init
  1299. 函数版本: 01.01
  1300. 创建作者:
  1301. 创建日期: 2015-07-04
  1302. 函数说明: X509证书初始化.
  1303. 参数说明:
  1304. 返回值: 成功返回0,失败返回-1
  1305. 修改记录:
  1306. */
  1307. int x509_init(void)
  1308. {
  1309. int ret = 0;
  1310. struct stat s;
  1311. extern unsigned char UserId[16];
  1312. //检查文件是否存在
  1313. if(sys_newstat(FILENAME_SM2_KEY_0,&s)==0)
  1314. {
  1315. return 0;
  1316. }
  1317. if(sys_newstat(FILENAME_SM2_KEY_1,&s) == 0)
  1318. {
  1319. return 0;
  1320. }
  1321. if(sys_newstat(FILENAME_SM2_KEY_2,&s)==0)
  1322. {
  1323. return 0;
  1324. }
  1325. if(sys_newstat(FILENAME_SM2_KEY_3,&s)==0)
  1326. {
  1327. return 0;
  1328. }
  1329. if(sys_newstat(FILENAME_X509_CER_0,&s) != 0)
  1330. {
  1331. return 0;
  1332. }
  1333. if(sys_newstat(FILENAME_X509_CER_1,&s) != 0)
  1334. {
  1335. return 0;
  1336. }
  1337. if(sys_newstat(FILENAME_X509_CER_2,&s) != 0)
  1338. {
  1339. return 0;
  1340. }
  1341. if(sys_newstat(FILENAME_X509_CER_3,&s) != 0)
  1342. {
  1343. return 0;
  1344. }
  1345. ret = base64file_to_binfile(FILENAME_X509_CER_0, FILENAME_X509_CER_TMP_0);
  1346. if(ret!=0)
  1347. {
  1348. rt_printf("%s: convert %s to bin error\n",__func__ , FILENAME_X509_CER_0);
  1349. goto ERR;
  1350. }
  1351. ret = base64file_to_binfile(FILENAME_X509_CER_1, FILENAME_X509_CER_TMP_1);
  1352. if(ret!=0)
  1353. {
  1354. rt_printf("%s: convert %s to bin error\n",__func__ , FILENAME_X509_CER_1);
  1355. goto ERR;
  1356. }
  1357. ret = base64file_to_binfile(FILENAME_X509_CER_2, FILENAME_X509_CER_TMP_2);
  1358. if(ret!=0)
  1359. {
  1360. rt_printf("%s: convert %s to bin error\n",__func__ , FILENAME_X509_CER_2);
  1361. goto ERR;
  1362. }
  1363. ret = base64file_to_binfile(FILENAME_X509_CER_3, FILENAME_X509_CER_TMP_3);
  1364. if(ret!=0)
  1365. {
  1366. rt_printf("%s: convert %s to bin error\n",__func__ , FILENAME_X509_CER_3);
  1367. goto ERR;
  1368. }
  1369. ret = x509_cer_to_sm2keybin(FILENAME_X509_CER_0, FILENAME_X509_CER_TMP_0, FILENAME_SM2_KEY_0);
  1370. if(ret!=0)
  1371. {
  1372. rt_printf("%s: generate %s error\n",__func__ , FILENAME_SM2_KEY_0);
  1373. goto ERR;
  1374. }
  1375. ret=x509_writetime_to_file(FILENAME_X509_TIME0, g_Certificate.tbsCertificate.validity.notBefore, g_Certificate.tbsCertificate.validity.notBefore_len, g_Certificate.tbsCertificate.validity.notAfter, g_Certificate.tbsCertificate.validity.notAfter_len);
  1376. if(ret!=0)
  1377. {
  1378. rt_printf("%s: generate %s error\n",__func__ , FILENAME_X509_TIME0);
  1379. goto ERR;
  1380. }
  1381. ret = x509_cer_to_sm2keybin(FILENAME_X509_CER_1, FILENAME_X509_CER_TMP_1, FILENAME_SM2_KEY_1);
  1382. if(ret!=0)
  1383. {
  1384. rt_printf("%s: generate %s error\n",__func__ , FILENAME_SM2_KEY_1);
  1385. goto ERR;
  1386. }
  1387. ret=x509_writetime_to_file(FILENAME_X509_TIME1, g_Certificate.tbsCertificate.validity.notBefore, g_Certificate.tbsCertificate.validity.notBefore_len, g_Certificate.tbsCertificate.validity.notAfter, g_Certificate.tbsCertificate.validity.notAfter_len);
  1388. if(ret!=0)
  1389. {
  1390. rt_printf("%s: generate %s error\n",__func__ , FILENAME_X509_TIME1);
  1391. goto ERR;
  1392. }
  1393. ret = x509_cer_to_sm2keybin(FILENAME_X509_CER_2, FILENAME_X509_CER_TMP_2, FILENAME_SM2_KEY_2);
  1394. if(ret!=0)
  1395. {
  1396. rt_printf("%s: generate %s error\n",__func__ , FILENAME_SM2_KEY_2);
  1397. goto ERR;
  1398. }
  1399. ret=x509_writetime_to_file(FILENAME_X509_TIME2, g_Certificate.tbsCertificate.validity.notBefore, g_Certificate.tbsCertificate.validity.notBefore_len, g_Certificate.tbsCertificate.validity.notAfter, g_Certificate.tbsCertificate.validity.notAfter_len);
  1400. if(ret!=0)
  1401. {
  1402. rt_printf("%s: generate %s error\n",__func__ , FILENAME_X509_TIME2);
  1403. goto ERR;
  1404. }
  1405. ret = x509_cer_to_sm2keybin(FILENAME_X509_CER_3, FILENAME_X509_CER_TMP_3, FILENAME_SM2_KEY_3);
  1406. if(ret!=0)
  1407. {
  1408. rt_printf("%s: generate %s error\n",__func__ , FILENAME_SM2_KEY_3);
  1409. goto ERR;
  1410. }
  1411. ret=x509_writetime_to_file(FILENAME_X509_TIME3, g_Certificate.tbsCertificate.validity.notBefore, g_Certificate.tbsCertificate.validity.notBefore_len, g_Certificate.tbsCertificate.validity.notAfter, g_Certificate.tbsCertificate.validity.notAfter_len);
  1412. if(ret!=0)
  1413. {
  1414. rt_printf("%s: generate %s error\n",__func__ , FILENAME_X509_TIME3);
  1415. goto ERR;
  1416. }
  1417. ret = write_data_to_file(FILENAME_USERID, UserId, sizeof(UserId));
  1418. if(ret!=0)
  1419. {
  1420. rt_printf("%s: write_data_to_file %s error\n",__func__ , FILENAME_USERID);
  1421. goto ERR;
  1422. }
  1423. ERR:
  1424. if(ret!=0)
  1425. {
  1426. rt_file_del(FILENAME_SM2_KEY_0);
  1427. rt_file_del(FILENAME_SM2_KEY_1);
  1428. rt_file_del(FILENAME_SM2_KEY_2);
  1429. rt_file_del(FILENAME_SM2_KEY_3);
  1430. }
  1431. return ret;
  1432. }
  1433. #endif