Java RSA 中字符串的密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22900570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:47:13  来源:igfitidea点击:

Key from String in Java RSA

javaandroidsecuritykeyrsa

提问by rgreso

I am using in my app RSA cryptography. To store generated public key I convert it to String and then save it in database.

我在我的应用程序中使用 RSA 加密。为了存储生成的公钥,我将其转换为字符串,然后将其保存在数据库中。

    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);

I save Strings publicKand privateK. My problem is, when I want to encrypt/decrypt text with RSA and use my saved Key in String format I don't know how to convert it to Key.

我保存字符串publicKprivateK. 我的问题是,当我想用​​ RSA 加密/解密文本并以字符串格式使用我保存的密钥时,我不知道如何将其转换为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;
}

Do you have any idea? Thanks a lot

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

回答by Rahil2952

To convert publicK(String) to Public Key do as below :

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

byte[] keyBytes = Base64.decode(publicK.getBytes("utf-8"));
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(spec);

To convert privateK(String) to Private Key do as below :

要将 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);

回答by Ysak

Could not able to comment on the previous post. I would like to know what is "clear" in

无法对之前的帖子发表评论。我想知道什么是“清晰”

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);

回答by user3005339

I can only assume the line:

我只能假设这条线:

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);

with "clear" was meant to be "keyBytes"

带有“clear”的意思是“keyBytes”