簡體   English   中英

如何使用Java確定用於從.pem文件生成私鑰的算法

[英]how to determine the algorithm used to generate a private key from a .pem file using java

我正在嘗試從PKCS#8格式的.pem文件中讀取私鑰,我遇到的問題是這類文件具有此標頭-----BEGIN PRIVATE KEY-----因此沒有有關用於實例化密鑰的算法的信息,我的問題是:
有沒有一種方法可以在不解碼密鑰的情況下(base64)知道算法,也可以查看算法修改器,也可以通過某種方式知道密鑰的長度。

使用Bouncy Castle並修改此答案中的代碼,我想出了這個來獲取您的答案。

注意:此代碼僅適用於未加密的私鑰。

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.Security;

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jcajce.provider.asymmetric.dsa.BCDSAPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPrivateKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

public class PemKeyInfo 
{
/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException 
{
    Security.addProvider(new BouncyCastleProvider());

    String privateKeyFileName = "C:\\privkeypk8.pem";

    File privateKeyFile = new File(privateKeyFileName); // private key file in PEM format
    PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
    Object object = pemParser.readObject();

    pemParser.close();

    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    PrivateKey privkey = null;

    if (object instanceof PrivateKeyInfo)
    {
       privkey = converter.getPrivateKey((PrivateKeyInfo) object);
    }
    if (privkey != null)
    {
       System.out.println("Algorithm: " + privkey.getAlgorithm()); // ex. RSA
       System.out.println("Format: " + privkey.getFormat()); // ex. PKCS#8
    }
    if (privkey instanceof BCRSAPrivateKey)
    {
       System.out.println("RSA Key Length: " + ((BCRSAPrivateKey)privkey).getModulus().bitLength()); // ex. 2048
    }
    if (privkey instanceof BCDSAPrivateKey)
    {
       System.out.println("DSA Key Length: " + ((BCDSAPrivateKey)privkey).getParams().getP().bitLength()); // ex. 2048
    }
    if (privkey instanceof BCECPrivateKey)
    {
       System.out.println("EC Key Length: " + ((BCECPrivateKey)privkey).getParams().getOrder().bitLength()); // ex. 256
    }
  }
}

更新:我已經編輯了上面的代碼以提供RSA,DSA和EC密鑰的密鑰長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM