load RSA Private Key from String - Android java.security

Android examples for java.security:RSA

Description

load RSA Private Key from String

Demo Code


//package com.java2s;
import android.util.Base64;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

import java.security.interfaces.RSAPrivateKey;

import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class Main {
    private static String RSA = "RSA";

    public static PrivateKey loadPrivateKey(String privateKeyStr)
            throws Exception {
        try {/*w w w.  j  a  va 2s. c om*/
            byte[] buffer = Base64.decode(privateKeyStr, Base64.DEFAULT);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("");
        } catch (InvalidKeySpecException e) {
            throw new Exception("?");
        } catch (NullPointerException e) {
            throw new Exception("?");
        }
    }
}

Related Tutorials