Skip to content Skip to sidebar Skip to footer

Android Encrypting String Using Rsa Public Key

I am working in a project where I have to encrypt password using RSA public key. I tried many samples and solutions from SO like as follows Android RSA encryption from public str

Solution 1:

try this.

publicstaticStringPUBLIC_KEY="YOUR PUBLIC KEY";

static String enccriptData(String txt)
{
  Stringencoded="";
  byte[] encrypted = null;
    try {
        byte[] publicBytes = Base64.decode(PUBLIC_KEY, Base64.DEFAULT);
        X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(publicBytes);
        KeyFactorykeyFactory= KeyFactory.getInstance("RSA");
        PublicKeypubKey= keyFactory.generatePublic(keySpec);
        Ciphercipher= Cipher.getInstance("RSA/ECB/PKCS1PADDING"); //or try with "RSA"
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        encrypted = cipher.doFinal(txt.getBytes());
        encoded = Base64.encodeToString(encrypted, Base64.DEFAULT);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return encoded;
}

EDIT:

You can use my code but read the comment of James K Polk, he's right

Solution 2:

The Kotlin Code for RSA encryption:

first of all you need to remove "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" and ... to have a clean text.

Just use this:

 publicKy = publicKy  .replace("\\r".toRegex(), "")
        .replace("\\n".toRegex(), "")
        .replace(System.lineSeparator().toRegex(), "")
        .replace("-----BEGIN PUBLIC KEY-----", "")
        .replace("-----END PUBLIC KEY-----", "")


    val encryptedString = enccriptData(input,publicKy)

' input ' is the text which you want to encrypt with your public key, then you need to use this method:

funenccriptData(txt: String, pk: String): String? {
    var encoded = ""var encrypted: ByteArray? = nulltry {
        val publicBytes: ByteArray = Base64.decode(pk, Base64.DEFAULT)
        val keySpec = X509EncodedKeySpec(publicBytes)
        val keyFactory: KeyFactory = KeyFactory.getInstance("RSA")
        val pubKey: PublicKey = keyFactory.generatePublic(keySpec)
        val cipher: Cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
        cipher.init(Cipher.ENCRYPT_MODE, pubKey)
        encrypted = cipher.doFinal(txt.toByteArray())
        encoded = Base64.encodeToString(encrypted, Base64.DEFAULT)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return encoded
}

Post a Comment for "Android Encrypting String Using Rsa Public Key"