加载以前存储的密钥在使用Java的BouncyCastle中失败

时间:2016-09-09 13:06:12

标签: java rsa bouncycastle

我正在使用Bouncy Castle生成Java的RSA密钥。我将此密钥存储到PKCS1文件中,并希望将此文件的另一部分加载回密钥文件对象。 我的密钥存储是

public static void writeKey(PemObject obj, String filename) throws IOException { 
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(filename)))
    {
        pemWriter.writeObject(obj);
        pemWriter.close();
    } catch (IOException ex) {
        Logger.getLogger(Conversion.class.getName()).log(Level.SEVERE, null, ex);
    }         
}

我使用

转换KeyPair对象
public static PemObject createPrivateObject(KeyPair key) throws Exception {
    return new PemObject("RSA PRIVATE KEY", key.getPrivate().getEncoded());
}

这个导出到文件中,一开始看起来不错。 OpenSSL能够读取此文件并显示有关密钥值的信息。 但是,稍后我尝试使用

从文件加载密钥
public static KeyPair readKeyPair(String path)
{
File privateKeyFile = new File(path);
    try (PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile))){


        Object object = pemParser.readObject();
        KeyPair kp;
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        kp = converter.getKeyPair((PEMKeyPair) object);
        pemParser.close();
        return kp;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PEMException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } 
return null;

}

当我尝试这个时,我收到一条错误消息

org.bouncycastle.openssl.PEMException: malformed sequence in RSA private key

(文字后的完整留言)

当我第二次看OpenSSl时,我看到OPENSSL在末尾打印了相同键的不同值, 文件中的键以

开头
-----BEGIN RSA PRIVATE KEY-----
MIIEugIBADAN[...]

OpenSSL输出

openssl rsa -text -in Userkey.pem

Private-Key: (2048 bit)
modulus:
[...]
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
MIIEoAIBAAKC[...]

用于如上所述生成和存储的密钥文件。如果我尝试手动将OpenSSL的输出复制到文件中并使用我的程序加载它,一切似乎都能正常工作。所以我假设writeKey子例程中有些错误,但我无法弄清楚这有什么问题。有人知道吗?

完整错误消息:

   org.bouncycastle.openssl.PEMException: malformed sequence in RSA private key
at org.bouncycastle.openssl.PEMParser$KeyPairParser.parseObject(Unknown Source)
at org.bouncycastle.openssl.PEMParser.readObject(Unknown Source)
at certificatemanagement.Crypto.readKeyPair(Crypto.java:257)
at certificatemanagement.GuiDesignController.CreateCertificatePressed(GuiDesignController.java:250)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.bouncycastle.openssl.PEMException: malformed sequence in RSA private key
at org.bouncycastle.openssl.PEMParser$RSAKeyPairParser.parse(Unknown Source)
... 70 more

1 个答案:

答案 0 :(得分:2)

Bouncy castle正在写PKC8格式的PEM文件,而不是PKCS1,它永远不会让你知道它没有做你期望的事情。

我不知道如何以PKCS1格式编写PEM文件。我很想知道,因为我经常花一个下午尝试这样做,然后才说服自己PCKS8如此优越,并且没有人真正需要PKCS1,而且没有人再次谈论PKCS1。

因此,如果您使用openssl命令:

openssl pkcs8 -topk8 -nocrypt -in private.pem

代替我认为你试过的那个(openssl rsa -in private.pem -check),你将获得与充气城堡所写内容相同的内容。在这里,我们还有一个命令,只是对它的功能有点聪明,并且不要告诉你"是的,你告诉我读pcks1 RSA文件,但是看,标题总是说谎,我 DO 看到它实际上是pkcs8,所以我只会把它读作pkcs8而且每个人都很开心吧?"

所以,你的代码应该适应于读取PCKS8之类的东西(从10年开始我就不做Java了,所以也许还有一些小东西要适应):

public static PemObject createPrivateObject(KeyPair key) throws Exception {
  return new PemObject("PRIVATE KEY", key.getPrivate().getEncoded());
}

[...]

public static KeyPair readKeyPair(String path) {
  File privateKeyFile = new File(path);
  try (PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile))){

    PrivateKeyInfo privkeyInfo = (PrivateKeyInfo)pemParser.readObject();
    PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec(privkeyInfo.getEncoded);
    RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(keyspec)
    pemParser.close();
    return kp;

} catch { ....