标签:
1 private static String getRSAPrivateKeyAsNetFormat(byte[] encodedPrivkey) {
2 try {
3 StringBuffer buff = new StringBuffer(1024);
4
5 PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(
6 encodedPrivkey);
7 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
8 RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey) keyFactory
9 .generatePrivate(pvkKeySpec);
10
11 buff.append("<RSAKeyValue>");
12 buff.append("<Modulus>"
13 + CodeUtils.base64Encode(removeMSZero(pvkKey.getModulus().toByteArray()))
14 + "</Modulus>");
15
16 buff.append("<Exponent>"
17 + CodeUtils.base64Encode(removeMSZero(pvkKey.getPublicExponent()
18 .toByteArray())) + "</Exponent>");
19
20 buff.append("<P>"
21 + CodeUtils.base64Encode(removeMSZero(pvkKey.getPrimeP().toByteArray()))
22 + "</P>");
23
24 buff.append("<Q>"
25 + CodeUtils.base64Encode(removeMSZero(pvkKey.getPrimeQ().toByteArray()))
26 + "</Q>");
27
28 buff.append("<DP>"
29 + CodeUtils.base64Encode(removeMSZero(pvkKey.getPrimeExponentP()
30 .toByteArray())) + "</DP>");
31
32 buff.append("<DQ>"
33 + CodeUtils.base64Encode(removeMSZero(pvkKey.getPrimeExponentQ()
34 .toByteArray())) + "</DQ>");
35
36 buff.append("<InverseQ>"
37 + CodeUtils.base64Encode(removeMSZero(pvkKey.getCrtCoefficient()
38 .toByteArray())) + "</InverseQ>");
39
40 buff.append("<D>"
41 + CodeUtils.base64Encode(removeMSZero(pvkKey.getPrivateExponent()
42 .toByteArray())) + "</D>");
43 buff.append("</RSAKeyValue>");
44
45 return buff.toString().replaceAll("[ \t\n\r]", "");
46 } catch (Exception e) {
47 System.err.println(e);
48 return null;
49 }
50 }
51
52 private static String getRSAPublicKeyAsNetFormat(byte[] encodedPublicKey) {
53 try {
54
55 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
56 RSAPublicKey pukKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(encodedPublicKey));
57
58 StringBuffer buff = new StringBuffer(1024);
59 buff.append("<RSAKeyValue>");
60 buff.append("<Modulus>"
61 + CodeUtils.base64Encode(removeMSZero(pukKey.getModulus().toByteArray()))
62 + "</Modulus>");
63 buff.append("<Exponent>"
64 + CodeUtils.base64Encode(removeMSZero(pukKey.getPublicExponent().toByteArray())) + "</Exponent>");
65 buff.append("</RSAKeyValue>");
66 return buff.toString().replaceAll("[ \t\n\r]", "");
67 } catch (Exception e) {
68 System.err.println(e);
69 return null;
70 }
71 }
把Java生成的RSA公钥、私钥转换成.NET使用的XML格式
标签:
原文地址:http://www.cnblogs.com/frankyou/p/4663801.html