Generating an RSA KeyPair and extracting modulus and exponent from Public Key in Android
我在android中生成了一个公钥对。现在,我需要将我的公钥发送回服务器,以便与RSA加密通信。但是,我正在与.NET服务器通信(在C)。因此,我需要以以下格式发送公钥:
1 | <RSAKeyValue><Modulus>Modulus In Base 64</Modulus><Exponent>Exponent in Base 64</Exponent></RSAKeyValue> |
我用以下代码生成密钥对:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static void generateKey() { try { final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); final KeyPair key = keyGen.generateKeyPair(); privateKey = key.getPrivate(); publicKey = key.getPublic(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } |
如何提取刚刚生成的PublicKey的模数和指数?
没有本地的Android方法来解决我的问题。为了提取生成的公钥的模数和指数,我使用了以下代码,它以Android公钥为输入,并以.NET XML格式返回:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public static String getPublicKeyAsXml(PublicKey publicKey) throws Exception { KeyFactory kf = KeyFactory.getInstance("RSA"); RSAPublicKeySpec ks = kf.getKeySpec(publicKey, RSAPublicKeySpec.class); BigInteger modulus = ks.getModulus(); BigInteger exponent = ks.getPublicExponent(); byte[] modByte = modulus.toByteArray(); byte[] expByte = exponent.toByteArray(); modByte = testBytes(modByte); expByte = testBytes(expByte); String encodedModulus = Base64.encodeToString(modByte, Base64.NO_WRAP); String encodedExponent = Base64.encodeToString(expByte, Base64.NO_WRAP); String publicKeyAsXML ="<RSAKeyValue>" + "<Modulus>" + encodedModulus +"</Modulus>" + "<Exponent>" + encodedExponent +"</Exponent>" + "</RSAKeyValue>"; return publicKeyAsXML; } |