lxyfirst

C++博客 首页 新随笔 联系 聚合 管理
  33 Posts :: 3 Stories :: 27 Comments :: 0 Trackbacks
keytool是java提供的管理密钥和签名的工具。数据储存在keystore文件中,即jks文件 。

1.创建rsa密钥对(公钥和私钥)并储存在keystore文件中:
keytool -genkeypair -keyalg RSA -keystore keystore.jks
2.从keystore文件中导出使用x509标准验证的数字证书,包含公钥。
keytool -exportcert -file cert.cer -keystore keystore.jks

keytool没有提供从keystore文件导出私钥的工具,需要编程实现此功能。
从keystore文件导出的证书、密钥都是DER格式,可以使用openssl工具转换成PEM格式。

openssl是一套强大的工具集,包含各种加解密算法,信息摘要及签名算法,密钥和证书管理等。
openssl使用的默认数据格式是PEM格式,也支持DER格式,可以进行互相转换。
1.genrsa命令用于创建私钥
openssl genrsa -out private.key
若需要对私钥加密,可以使用 -des -des3等参数。
2.rsa命令用于对密钥管理,格式转换
使用私钥创建对应的公钥
openssl rsa -in private.key -out public.key -pubout
将DER格式公钥转换为PEM格式
openssl rsa -in public.key.der -inform der -pubin -outform pem -out public.key
3.x509命令用于管理x509标准的证书
将DER格式证书转换成PEM格式
openssl x509 -in cert.cer -inform der -outform PEM -out cert.crt
从证书中导出公钥
openssl x509 -in cert.crt -pubkey -out public.key
4.pkcs8,pkcs12命令用于管理私钥的pkcs编解码
将密钥使用pkcs8加密
openssl pkcs8 -in private.key  -nocrypt -topk8 -out private.p8
将pkcs8密钥解密
openssl pkcs8 -in decrypted.p8 -nocrypt


md5rsa代码示例
function rsa_md5_public_verify($data,$signature,$pubkey)
{
    
$key=openssl_get_publickey($pubkey);
    
if(!$keyreturn false ;
    
$crypted_sig = base64_decode(pack("H*",$signature) );
    
if(!openssl_public_decrypt($crypted_sig,$original_sig,$key)) return false ;
   
//md5 appending ?
    ifsubstr(bin2hex($original_sig),-32!=  md5($data)  ) return false ;
    
return true ;

}

function rsa_md5_public_sign($data,&$signature,$pubkey)
{
    
$key=openssl_get_publickey($pubkey);
    
if(!$keyreturn false ;
    
$original_sig = pack("H*",md5($data));
    
if(!openssl_public_encrypt($original_sig,$crypted_sig,$key)) return false ;
    
$signature = bin2hex(base64_encode($crypted_sig)) ;
    
return true ;

}

function rsa_md5_private_verify($data,$signature,$prikey)
{
    
$key=openssl_get_privatekey($prikey);
    
if(!$keyreturn false ;
    
//var_dump(pack("H*",$crypted));
    $crypted_sig = base64_decode(pack("H*",$signature) );
    
if(!openssl_private_decrypt($crypted_sig,$original_sig,$key)) return false ;
    
//md5 appending ?
    ifsubstr(bin2hex($original_sig),-32!=  md5($data)  ) return false ;
    
return true ;

}

function rsa_md5_private_sign($data,&$signature,$prikey)
{
    
$key=openssl_get_privatekey($prikey);
    
if(!$keyreturn false ;
    
$original_sig = pack("H*",md5($data));
    
if(!openssl_private_encrypt($original_sig,$crypted_sig,$key)) return false ;
    
$signature = bin2hex(base64_encode($crypted_sig)) ;
    
return true ;

}


var_dump(rsa_md5_private_sign($original,$sig,$prikey) );
var_dump($sig) ;
var_dump(rsa_md5_public_verify($original,$sig,$pubkey) );







posted on 2011-04-15 14:53 star 阅读(8522) 评论(1)  编辑 收藏 引用

Feedback

# re: openssl和keytool对rsa密钥的管理机制及用法 2011-11-18 13:32 hong
对应到linux下c代码是什么,谢谢  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理