Problem while parsing String to Public Key; Invalid key format

时间:2019-04-16 23:23:28

标签: java base64 rsa public-key pgp

I'm trying to 'parse' a alphanumerical String to a PublicKey object in Java. I want to read the modulus and the exponent from that key. Im a newbie in this, so I dont know exactly what I should do here.

I tried by reading the file wich contains the String, or by just reading the file with InputStream and the like, and always keep going until the last part; parsing bytes to PublicKey.

This is the Key Im trying to parse;

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: Encryption Desktop 10.3.2 (Build 15495)

mQENBFyL1ngBCADPZR4FPDxi9v5wNVXDksXzo9IEQvFoQIIfmGaomQ8PrAZHH2jb
nUGK6Y56p/Mlxz3uqfOR0fyBNuq/beszk/jChcy9sqCF3TwKBOdWVcXiIU/XiS0V
...
+FnyI/aT7n+jXBpQSWiyHQyM9RfS0rBeO9w7Q4nWwMyAEHfYxqaajYgJZ+N+Jw==
=Adx/
-----END PGP PUBLIC KEY BLOCK-----

And this is the code i'been trying;

fis = new FileInputStream(FilePath);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);

while ((line = br.readLine()) != null) {
rd+=line+",";
}
partes=rd.split(",");
String llaveses="";
int i=2;
while (partes.length>i){
    if (i == partes.length-1){
    llaveses+="";
    }else
    llaveses+=partes[i];
    i++; }

byte[] bytepuk = llaveses.getBytes();
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytepuk);
KeyFactory kfRSA = KeyFactory.getInstance("RSA");
PublicKey pukrsa=kfRSA.generatePublic(spec); //i always got stuck in this part

I have tried with this, as well with PGPPublicKey, but nope, it alwayes keep saying 'invalid key format'

I just want to get those two datas; modulus and exponent Any help or recommendation would be great! Also, sorry for my poor english!

2 个答案:

答案 0 :(得分:0)

使用Java,您可以通过这种方式使用著名的Bouncy Castle加密库来解析PGP公钥。

在您的问题中,FilePath是包含PEM编码的公共密钥的文件的路径,因此这是一种获取公共指数和模量值的方法:

  • 创建一个解析文件路径内容的密钥环对象;
  • 从钥匙圈中提取公钥;
  • 将通用公钥对象转换为 RSAPublicBCPGKey 的实例,以访问 getPublicExponent() getModulus()方法。
  • li>

这是代码段。

package net.fenyo.tstpgp;

import java.io.*;
import org.bouncycastle.bcpg.*;
import org.bouncycastle.openpgp.*;
import org.bouncycastle.openpgp.jcajce.*;

public class App {
    static String FilePath = "d:/temp/publickey.pem";

    public static void main(String[] args) throws IOException, PGPException {
        // Import the PEM encoded key in a key ring
        JcaPGPPublicKeyRingCollection pgpPub = new JcaPGPPublicKeyRingCollection(org.bouncycastle.openpgp.PGPUtil
                .getDecoderStream(new FileInputStream(new File(FilePath))));
        // Extract the public key from the ring
        PGPPublicKey pk = pgpPub.getKeyRings().next().getPublicKey();
        RSAPublicBCPGKey rsa = (RSAPublicBCPGKey) pk.getPublicKeyPacket().getKey();

        // Display the components of the public key
        System.out.println("public exponent: " + rsa.getPublicExponent().toString());
        System.out.println("modulus: " + rsa.getModulus().toString());
    }
}

这是该程序输出的示例,其文件 d:/temp/publickey.pem 的内容已从此处下载:https://keyserver.pgp.com/vkd/DownloadKey.event?keyid=0x5F6C8AE0F08B18EC

public exponent: 65537
modulus: 864707173482092744188671562103373011522752303482519808998088798903008001989099675905283831755832233822390078023832521726213457271249972815470211175966041907569318308362891570478941689686712697599623242011017193503964284513039591891526529083515353888885379235878670749376434323941202586223991854576398690573826518569769985809172651040238653272623223118871290893821208919901304705818060395766177710540558136309696633947940763393190279817250884876978530480176563952524356940770342282654575132991815388460879205229175539573644598040510846046356206518680485904082394070023094993115791279506109927248743485104551955556126256899738972837743577201916815523009590547379892261434498517119972252725514435930097571692392590872567503156038414424344470094696986970708719252723773350549916905691632234402052848270487256520247608379181338474223362079571903909236852815812080392096829534242568109033526006705931306007816143593663131528165731422403611912314397882216433246741610889521014679759861466346273746749512271029719491507151898623753390849376017894676856788535056943964836442355399016103191720725346349409014858505159766120737574239682242298505299052720937352185330272669848438756037873927573782283883754416499218933913671945750838607217911481

注意:这是一个maven pom文件的示例,该文件用于自动下载Bouncy Castle依赖关系并编译该程序:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.fenyo</groupId>
  <artifactId>tstpgp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>tstpgp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpg-jdk15on</artifactId>
      <version>1.61</version>
    </dependency>
  </dependencies>
</project>

答案 1 :(得分:-1)

Your while loop is a bit confusing, so for simplicity sake lets assume that your alphanumeric string is stored in the your_string variable. Try the following code

String public_key = your_string.replace("-----BEGIN PUBLIC KEY-----\n", "").replace("-----END PUBLIC KEY-----", "");
byte[] encoded_public_key = Base64.decode(publicKey);    
X509EncodedKeySpec spec = new X509EncodedKeySpec(encoded_public_key);
KeyFactory keyfactory = KeyFactory.getInstance("RSA");
keyfactory.generatePublic(spec)
相关问题