在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
原来项目中用openresty nginx+lua实现server,lua调用c动态链接库,来使用openss做签名,并生成130字节(128签名+2位自定义字节)长度的文件。 nginx: location /get/key { content_by_lua_file '/data/www/sign.lua'; } sign.lua local ffi = require "ffi" --动态链接gen_sig_ex_x.c,load("")名字规则,lib***.so local gs = ffi.load("sin") ffi.cdef[[ int gen_main(char *param,unsigned char *signature) ]] local param_ = ngx.var.arg_param if param_ then local signature = ffi.new("unsigned char[130]", {}) local cpsn = ffi.new("char[20]", param_) gs.gen_main(param_, signature) ngx.header["Content-Disposition"] = "attachment; filename=" .. string.format("%s.%d.key", psn, key) ngx.header["Content-Length"] = 130 ngx.say(ffi.string(signature, 130)) else ngx.header.content_type = "text/html" ngx.say("the param is not empty") end 对于sin.so用c与openssl实现了私钥签名,并使用RSA结构秘钥,为顺利得到pkcs8,在程序中通过如下代码逆化了该格式的私钥。并通过命令得到公钥。
//根据RSA结构私钥构建KEY对象,获取私钥公钥base64: FILE *filename = NULL; filename = fopen("/data/www/unlock.lua/privateKey.pem", "wb"); //生成私钥接口 PEM_write_RSAPrivateKey(filename, key, NULL, NULL, 0, NULL, NULL); fclose(filename); unsigned char *n_b = (unsigned char *)calloc(RSA_size(key), sizeof(unsigned char)); unsigned char *e_b = (unsigned char *)calloc(RSA_size(key), sizeof(unsigned char)); int n_size = BN_bn2bin(key->n, n_b); int b_size = BN_bn2bin(key->e, e_b); RSA *pubrsa = RSA_new(); pubrsa->n = BN_bin2bn(n_b, n_size, NULL); pubrsa->e = BN_bin2bn(e_b, b_size, NULL); FILE *publicKey = NULL; publicKey = fopen("/data/www/unlock.lua/publicKey.pem", "wb"); PEM_write_RSAPublicKey(publicKey, pubrsa); fclose(publicKey); RSA_free(pubrsa); ====java实现签名核心代码: package com.smartisan.genkey_sig.util; import org.apache.commons.codec.binary.Base64; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; /** * desc: * * @author guozefeng@*********.com * @since 2017/8/11 */ public class RsaUtil { public static final String KEY_ALGORITHM = "RSA"; public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; public static byte[] sign(byte[] data, String privateKey) { try { byte[] keyBytes = Base64.decodeBase64((privateKey)); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); // KEY_ALGORITHM 指定的加密算法 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 取私钥匙对象 PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec); // 用私钥对信息生成数字签名 Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(priKey); signature.update(data); return signature.sign(); } catch (Exception ex) { throw new RuntimeException(ex); } } public static byte[] sign(String data, String privateKey) { return sign(data.getBytes(StandardCharsets.UTF_8), privateKey); } }
|
请发表评论