Generating RSA keys in PKCS#1 format in Java

前端 未结 6 658
有刺的猬
有刺的猬 2020-11-28 08:33

When I generate an RSA key pair using the Java API, the public key is encoded in the X.509 format and the private key is encoded in the PKCS#8 format. I\'m looking to encod

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 08:42

    I was trying to generate OpenSSL-friendly RSA public keys in DER format using BountyCastle J2ME library ported to BlackBerry, my code:

    public void testMe() throws Exception {
      RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
      generator.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001),
                     new SecureRandom(), 512, 80));
      AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
    
      RSAKeyParameters params =  (RSAKeyParameters) keyPair.getPublic();
      RSAPublicKeyStructure struct = new RSAPublicKeyStructure(params.getModulus(), 
                                                               params.getExponent());
    
      SubjectPublicKeyInfo info = 
        new SubjectPublicKeyInfo(new AlgorithmIdentifier("1.2.840.113549.1.1.1"), 
                                 struct);
    
      byte[] bytes = info.getDEREncoded();
    
      FileOutputStream out = new FileOutputStream("/tmp/test.der");
    
      out.write(bytes);
      out.flush();
      out.close();
    }
    

    Key was still incorrect:

    $ openssl asn1parse -in test.der -inform DER -i
    0:d=0  hl=2 l=  90 cons: SEQUENCE          
    2:d=1  hl=2 l=  11 cons:  SEQUENCE          
    4:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
    15:d=1  hl=2 l=  75 prim:  BIT STRING     
    

    I changed org.bouncycastle.asn1.x509.AlgorithmIdentifier

    public AlgorithmIdentifier(
        String     objectId)
    {
        this.objectId = new DERObjectIdentifier(objectId);
        // This line has been added
        this.parametersDefined = true;
    }
    

    And now have nice key:

    $ openssl asn1parse -in test.der -inform DER -i
    0:d=0  hl=2 l=  92 cons: SEQUENCE          
    2:d=1  hl=2 l=  13 cons:  SEQUENCE          
    4:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
    15:d=2  hl=2 l=   0 prim:   NULL              
    17:d=1  hl=2 l=  75 prim:  BIT STRING 
    

    Which can be used to encrypt:

    $ echo "123" | openssl rsautl -pubin  -inkey test.der -encrypt -keyform DER -out y
    $ wc -c y
    64 y
    

提交回复
热议问题