get RSA Public Key - Android java.security

Android examples for java.security:RSA

Description

get RSA Public Key

Demo Code


import android.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;

public class Main{
    public static RSAPublicKey getPublicKey(String xmlDsig)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        boolean hasMod = xmlDsig.contains(Tags.MOD_START)
                && xmlDsig.contains(Tags.MOD_END);
        if (!hasMod)
            throw new IllegalArgumentException(
                    "RSA modulus not found in response");

        boolean hasExp = xmlDsig.contains(Tags.EXP_START)
                && xmlDsig.contains(Tags.EXP_END);
        if (!hasExp)
            throw new IllegalArgumentException(
                    "RSA exponent not found in response");

        String mod = xmlDsig.substring(xmlDsig.indexOf(Tags.MOD_START)
                + Tags.MOD_START.length(), xmlDsig.indexOf(Tags.MOD_END));
        String exp = xmlDsig.substring(xmlDsig.indexOf(Tags.EXP_START)
                + Tags.EXP_START.length(), xmlDsig.indexOf(Tags.EXP_END));

        BigInteger modulus = new BigInteger(1, Base64.decode(mod,
                Base64.DEFAULT));//from   ww w.  ja  va  2 s.  c  o  m
        BigInteger exponent = new BigInteger(1, Base64.decode(exp,
                Base64.DEFAULT));

        RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        RSAPublicKey pub = (RSAPublicKey) factory.generatePublic(spec);

        return pub;
    }
}

Related Tutorials