Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key from String in Java RSA

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

    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 publicK and 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.

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

like image 615
rgreso Avatar asked Apr 06 '14 22:04

rgreso


People also ask

How can I get RSA public key from string?

getPublicExponent(); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent); KeyFactory kf = KeyFactory. getInstance("RSA"); PublicKey generatedPublic = kf. generatePublic(keySpec); System.

How can RSA be used to generate key pairs?

You can generate RSA key pairs in the encrypted form on a workstation with a 4755 cryptographic adapter or a 4764 PCIX Cryptographic Coprocessor installed. A workstation with a 4758 PCI Cryptographic Coprocessor can also be used.


1 Answers

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

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 :

byte[] keyBytes = Base64.decode(privateK.getBytes("utf-8"));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priv = fact.generatePrivate(keySpec);
like image 174
baldguy Avatar answered Sep 21 '22 16:09

baldguy