Java RSA中String的键

我在我的应用程序中使用RSA加密.要存储生成的公钥,我将其转换为String,然后将其保存在数据库中.
Key publicKey=null;
    Key privateKey=null;

    KeyPair keyPair=RsaCrypto.getKeyPairRSA(1024);
    publicKey=keyPair.getPublic();
    privateKey=keyPair.getPrivate();



    String publicK=Base64.encodetoString(publicKey.getEncoded(),Base64.DEFAULT);
    String privateK=Base64.encodetoString(privateKey.getEncoded(),Base64.DEFAULT);

我保存了Strings publicK和privateK.
我的问题是,当我想用​​RSA加密/解密文本并使用我保存的Key in String格式时,我不知道如何将其转换为Key.

public static String encrypt(Key publicKey,String inputText){
    byte[]encodedBytes=null;
    String encryptedText="";
    try {
        Cipher cipher=Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        encodedBytes=cipher.doFinal(inputText.getBytes());
    } catch (Exception e) {Log.e("Error","RSA encryption error");  }

    encryptedText=Base64.encodetoString(encodedBytes,Base64.DEFAULT);
    return encryptedText;
}

你有什么主意吗?
非常感谢

解决方法

要将publicK(String)转换为Public Key,请执行以下操作:
byte[] keyBytes = Base64.decode(publicK.getBytes("utf-8"));
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(spec);

要将privateK(String)转换为私钥,请执行以下操作:

byte[] keyBytes = Base64.decode(privateK.getBytes("utf-8"));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priv = fact.generatePrivate(keySpec);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...