Android保存RSA私钥和公钥 [英] Android Save RSA Private and Public Key
问题描述
我需要保存我的RSA私钥和公钥。在这里我创建它。
I need to save my RSA private and public key. Here I create it.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
现在我想在下次使用这两个密钥。所以它们应该存储在设备上。
Now I want to use both keys the next time. So they should be stored on the device.
byte[] publicKeyBytes = publicKey.getEncoded();
byte[] privateKeyBytes = privateKey.getEncoded();
所以我可以获得字节数组然后将它们保存为文本文件。
然后下次我读它并将其转换回字节数组。
So I can get the Byte Arrays and then I save them as a text file. Then the next time i read it and convert it back to the byte Array.
现在我的问题:如何将字节数组转换回键?
Now my question: How can i convert a byte array back to a key?
这不起作用:
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
publicKey = keyFactory.generatePublic(spec);
spec = new X509EncodedKeySpec(privateKeyBytes);
privateKey = keyFactory.generatePrivate(spec);
在LogCat上,这将显示:
On LogCat, this is going to be display:
必须使用RSAPublicKeySpec或PKCS8EncodedKeySpec;是
java.security.spec.X509EncodedKeySpec
Must use RSAPublicKeySpec or PKCS8EncodedKeySpec; was java.security.spec.X509EncodedKeySpec
这个代码有什么问题吗?
Any ideas whats wrong with this code?
感谢您的帮助。
推荐答案
尝试使用 PKCS8EncodedKeySpec $公钥的c $ c>用于私钥。
RSAPublicKeySpec
,而不是 X509EncodedKeySpec
两者。
请注意,将密钥保存到文本文件可能不是最安全的想法。 Android提供了一个很好用的 KeyStore Api ,它很容易使用。
Please also note that saving keys to a text file might not be the most secure idea. Android provides a nice KeyStore Api, which is easy to use.
这篇关于Android保存RSA私钥和公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!