थॉमस Pornin के समाधान अनिवार्य रूप से सही है लेकिन मेरे लिए काम नहीं किया क्योंकि तरीकों, जैसे getModulus(), BigInteger को वापस करें जिसके परिणामस्वरूप एक संख्यात्मक स्ट्रिंग होती है, जबकि मानक .NET XML प्रारूप बेस 64 एन्कोडेड बाइट्स का उपयोग करता है।
मैंने बाइट प्राप्त करने के लिए "getModulus()। ToByteArray()" का उपयोग किया। तब मुझे सरणी के पहले तत्व को ट्रिम करने की आवश्यकता थी (एक्सपोनेंट को छोड़कर) क्योंकि वहां एक अवांछित शून्य बाइट है। (मुझे लगता है क्योंकि BigInteger पर हस्ताक्षर किए गए हैं, यह एक अतिरिक्त बाइट जोड़ता है ताकि अग्रणी बिट संकेत इंगित कर सके)।
मैंने गिटहब पर the code पोस्ट किया है।
मुख्य सा है:
static String getPrivateKeyAsXml(PrivateKey privateKey) throws Exception{
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
RSAPrivateCrtKeySpec spec = keyFactory.getKeySpec(privateKey, RSAPrivateCrtKeySpec.class);
StringBuilder sb = new StringBuilder();
sb.append("<RSAKeyValue>" + NL);
sb.append(getElement("Modulus", spec.getModulus()));
sb.append(getElement("Exponent", spec.getPublicExponent()));
sb.append(getElement("P", spec.getPrimeP()));
sb.append(getElement("Q", spec.getPrimeQ()));
sb.append(getElement("DP", spec.getPrimeExponentP()));
sb.append(getElement("DQ", spec.getPrimeExponentQ()));
sb.append(getElement("InverseQ", spec.getCrtCoefficient()));
sb.append(getElement("D", spec.getPrivateExponent()));
sb.append("</RSAKeyValue>");
return sb.toString();
}
static String getElement(String name, BigInteger bigInt) throws Exception {
byte[] bytesFromBigInt = getBytesFromBigInt(bigInt);
String elementContent = getBase64(bytesFromBigInt);
return String.format(" <%s>%s</%s>%s", name, elementContent, name, NL);
}
static byte[] getBytesFromBigInt(BigInteger bigInt){
byte[] bytes = bigInt.toByteArray();
int length = bytes.length;
// This is a bit ugly. I'm not 100% sure of this but I presume
// that as Java represents the values using BigIntegers, which are
// signed, the byte representation contains an 'extra' byte that
// contains the bit which indicates the sign.
//
// In any case, it creates arrays of 129 bytes rather than the
// expected 128 bytes. So if the array's length is odd and the
// leading byte is zero then trim the leading byte.
if(length % 2 != 0 && bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, length);
}
return bytes;
}
static String getBase64(byte[] bytes){
return Base64.getEncoder().encodeToString(bytes);
}
एक कुंजी युग्म कोई एन्क्रिप्शन के साथ इस तरह से भंडारण (इस प्रकार अपनी निजी कुंजी उजागर छोड़कर) एक सच में, सच बुरा विचार है। – Hut8
कुंजीपटल के लिए अपना स्वयं का रैपर क्लास बनाएं जो Serializable इंटरफ़ेस लागू करता है। 'ReadObject()', 'writeObject()', और 'readObjectNoData()' विधियों को ओवरराइड करें। –
@ bowenl2 क्या आप अन्य प्लेटफार्मों के साथ एकीकृत करने के लिए कोई अच्छा तरीका सुझा सकते हैं? – dvl