java加载私钥_如何从文件加载RSA私钥

如何从文件加载RSA私钥

我正在研究SAML 1.1断言消费者服务的测试工具。测试必须生成签名的SAMLResponse并将其提交给Base64中编码的ACS。ACS必须能够使用X509公共证书验证签名的消息。

我能够构建SAMLResponse,添加必要的断言等。但是当我尝试签署对象时,我遇到了问题。这是我当前代码的片段:String certPath = "mycert.pem";File pubCertFile = new File(certPath);BufferedInputStream bis = null;try {

bis = new BufferedInputStream(new FileInputStream(pubCertFile));} catch(FileNotFoundException e) {

throw new Exception("Could not locate certfile at '" + certPath + "'", e);}CertificateFactory certFact = null;Certificate cert = null;try {

certFact = CertificateFactory.getInstance("X.509");

cert = certFact.generateCertificate(bis);} catch(CertificateException e) {

throw new Exception("Could not instantiate cert", e);}bis.close();ArrayList certs = new ArrayList();certs.add(cert);String keyPath = "mykey.pem";File privKeyFile = new File(keyPath);try {

bis = new BufferedInputStream(new FileInputStream(privKeyFile));} catch(FileNotFoundException e) {

throw new Exception("Could not locate keyfile at '" + keyPath + "'", e);}byte[] privKeyBytes = new byte[(int)privKeyFile.length()];bis.read(privKeyBytes);bis.close();KeyFactory keyFactory = KeyFactory.getInstance("RSA");KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(ks);samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), privKey, certs);

错误发生在倒数第二行。我在控制台中看到以下内容:java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

虽然不是习惯性的或安全的,但为了这个帖子,我提供了我正在使用的公共证书和私钥。一旦问题解决了,我当然会重新创建新的。:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值