简体   繁体   中英

Java: Error while converting Public Key from byte array to string and back

I have this strange error which I can't find a solution to fix.

So I generate a public-private key pair, convert it to byte-array and after that recover the original key from that by array. No errors

  {  

     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
     kpg.initialize(1024);
     KeyPair keyPair = kpg.generateKeyPair();
     PublicKey pub = keyPair.getPublic();
     byte[] pubBytes = pub.getEncoded();

     try
     {
         // to recover the key
        KeyFactory kf = KeyFactory.getInstance("RSA");

        PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pubBytes));

     }
     catch(Exception e)
     {
         System.out.println(e.getMessage());
     }

     System.out.println("Finish");

After that I repeat the same steps, but before recovering the key, I convert the byte array to string and after that back. In this case I get error.

     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
     kpg.initialize(1024);
     KeyPair keyPair = kpg.generateKeyPair();
     PublicKey pub = keyPair.getPublic();
     byte[] pubBytes = pub.getEncoded();

     try
     {

         String pub1 = new String(pubBytes, "UTF-8"); 

         byte[] pub2 = pub1.getBytes("UTF-8");

         // to recover the key
        KeyFactory kf = KeyFactory.getInstance("RSA");

        PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pub2));

     }
     catch(Exception e)
     {
         System.out.println(e.getMessage());
     }

The error occurs a the line:

PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pub2));

and it says:

java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=111, too big.

Does anyone know how to fix and why in general this happens? The message says invalid key exception, however since it worked i the first case, I am more inclined that something wrong happens during byte conversion. It does not make sense at all.

A key contains arbitrary bytes. And those bytes don't necessarily represent valid UTF8 characters. So you shouldn't transform them to a String, because that is a lossy conversion. If you really need a String, then use Hex or Base64 encoding.

To make you realize what the error is, let's say that you use ASCII instead of UTF8. ASCII characters go from 0 to 127. All the other 128 byte values don't represent valid characters. So if the key contain any of those values, the transformation to a String loses them. It's basically the same thing with any encoding (except, IIRC, ISO8859-1).

我之前遇到过类似的问题,我忘记了导入包含项目中密钥的配置文件,我的配置文件是conf / XX.properties。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM