当前位置: 代码迷 >> J2EE >> 怎么将ASCII编码RSA公钥转换为publickey对象`
  详细解决方案

怎么将ASCII编码RSA公钥转换为publickey对象`

热度:54   发布时间:2016-04-22 00:25:38.0
如何将ASCII编码RSA公钥转换为publickey对象``?
如何将ASCII编码RSA公钥转换为publickey对象``?

页面传到后台是公钥的ASCII编码字符串.
现在在后台这么写的:
Java code
            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKey.getBytes());            KeyFactory keyFactory = KeyFactory.getInstance("RSA");            RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);


执行的时候异常:java.security.InvalidKeyException: invalid key format

请教下应该怎么写``

------解决方案--------------------
基本代码是这样的,但是你贴出来的那个公钥有问题,解析不了。我用随机产生的公钥是可以还原的。

Java code
import java.security.KeyFactory;import java.security.PublicKey;import java.security.spec.KeySpec;import java.security.spec.X509EncodedKeySpec;public class Cert {    public static void main(String[] args) throws Exception {        String str = "30818902818100B6FA647C106B69AD474145F0A5EE8FC7B760" +                 "E77B049CCB059C0D8E7B15DBE63DD4B260A84E6D1474855328" +                 "7A022A39C0F69740978088660CC7E26069FE11BFE0BD2F2967" +                 "71887AF632FB2F5DB0452ADD4D8E00DBC679A9AB95C61CDB2B" +                 "4B072E37737140DD0131745FCACDF8638309E552F03F0CD00A" +                 "6313EF72E8E19051BE290203010001";                System.out.println(str.length());        byte[] keyBytes = toBytes(str);                KeySpec keySpec = new X509EncodedKeySpec(keyBytes);        KeyFactory factory = KeyFactory.getInstance("RSA");        PublicKey publicKey = factory.generatePublic(keySpec);    }        private static byte[] toBytes(String str) {        if(str == null) {            throw new IllegalArgumentException("binary string is null");        }        char[] chs = str.toCharArray();        byte[] bys = new byte[chs.length / 2];        int offset = 0;        int k = 0;        while(k < chs.length) {            bys[offset++] = (byte)((toInt(chs[k++]) << 4) | toInt(chs[k++]));        }        return bys;    }        private static int toInt(char a) {        if(a >= '0' && a <= '9') {            return a - '0';        }        if(a >= 'a' && a <= 'f') {            return a - 'a' + 10;        }        if(a >= 'A' && a <= 'F') {            return a - 'A' + 10;        }        throw new IllegalArgumentException("parameter \"" + a + "\"is not hex number!");    }}
  相关解决方案