praveenLal
praveenLal

Reputation: 94

RSA encryption with key and exponent in android

I have a private key and exponent, i need to implement RSA encryption of string in android application. How can i do this? Is there any default class for the RSA encryption?

Upvotes: 1

Views: 1217

Answers (1)

Snicolas
Snicolas

Reputation: 38168

public void saveToFile(String fileName, BigInteger mod, BigInteger exp)
        throws IOException {
    ObjectOutputStream oout = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream(fileName)));
    try {
        oout.writeObject(mod);
        oout.writeObject(exp);
    } catch (Exception e) {
        throw new IOException("Unexpected error", e);
    } finally {
        oout.close();
    }
}

PublicKey ReadPublicKeyFromFile(String keyFileName) throws IOException {
    InputStream in = RSACrypt.class.getClassLoader().getResourceAsStream(keyFileName);
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
            in));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pubKey = fact.generatePublic(keySpec);
        return pubKey;
    } catch (Exception e) {
        throw new RuntimeException("Spurious serialisation error", e);
    } finally {
        oin.close();
    }
}

from http://www.developpez.net/forums/d1001867/java/developpement-web-java/besoin-daide-rsa/

Upvotes: 2

Related Questions