【问题标题】:How to read contents of a password protected file?如何读取受密码保护的文件的内容?
【发布时间】:2015-02-05 11:03:52
【问题描述】:

我正在尝试从受密码保护的 PEM 文件中读取数据,以从这些数据中生成公钥和私钥。我有密码,我需要在打开文件时传递该密码。但我在 java 中没有任何选项可以做到这一点。

在这方面需要紧急援助。如果我能得到一个代码示例就更好了。

已编辑:

我当前的代码是 -

public void readPrivateKey(String filePath)

{
  File fp = new File(filePath);

  FileInputStream fis = new FileInputStream(fp);

 DataInputStrean dis = new DataInputStream(fis);
byte [] keyBytes = new byte [(int) fp.length()];
dis.readFully(keyBytes);
dis.close();
String temp = new String(keyBytes);
String privateKeyPem = removeUnnecessaryTags(temp); //this function returns a string after removing String like this "BEGIN......."
byte[] decoded = Base64.decode(privateKeyPem);
ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence.fromByteArray(decoded);
Enumeration <?> e = primitive.getObjects();

BigInteger bigInt = ((DERInteger)e.NextElement()).getValue();
int version = bigInt.intValue();
BigInteger modulus = ((DERInteger)e.NextElement()).getValue();
BigInteger publicExp = ((DERInteger)e.NextElement()).getValue();
//... all the values has been retrieved in this way
}

【问题讨论】:

标签: java file pem


【解决方案1】:

我相信您正在了解 RSA 密钥对。

你可以不用像这样使用Java,

openssl rsa -in MYFILE.pem -pubout > MYFILE.pub
ssh-keygen -f MYFILE.pub -i -m PKCS8

如果您需要在 Java 中执行此操作,请参阅 cmets 中 @m0skit0 提供的链接。


【讨论】:

  • 但是我的密钥没有加密。该文件仅受密码保护。这是否意味着如果文件受密码保护,那么密钥也会被加密?
  • 好吧,我在我的代码的编辑部分分享我的代码。那我想你会明白我的意思的:)
猜你喜欢
  • 2013-11-09
  • 2011-01-01
  • 2019-12-03
  • 1970-01-01
  • 2018-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
  • 2016-06-21
相关资源
最近更新 更多