日期:2014-05-19 浏览次数:20882 次
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKey.getBytes()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);
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!"); } }