generate RSA Private Key - Android java.security

Android examples for java.security:RSA

Description

generate RSA Private Key

Demo Code


//package com.java2s;
import java.math.BigInteger;
import java.security.KeyFactory;

import java.security.PrivateKey;

import java.security.spec.RSAPrivateCrtKeySpec;

public class Main {
    private static PrivateKey privateKey;

    public static PrivateKey getPrivateKey() {
        return privateKey;
    }/*from   w  w w  .  j  a v  a  2 s  .  com*/

    public static PrivateKey getPrivateKey(String priKeyData)
            throws Exception {
        /*
         * n:512 e:512 d:512 p:256 q:256 dmp1:256 dmq1:256 iqmp:256
         */
        BigInteger modulus = new BigInteger(
                priKeyData.substring(8, 512 + 8), 16);
        BigInteger publicExponent = new BigInteger(priKeyData.substring(
                512 + 8, 512 + 8 + 512), 16);
        BigInteger privateExponent = new BigInteger(priKeyData.substring(
                512 + 8 + 512, 512 + 8 + 512 + 512), 16);
        BigInteger primeP = new BigInteger(priKeyData.substring(
                512 + 8 + 512 + 512, 512 + 8 + 512 + 512 + 256), 16);
        BigInteger primeQ = new BigInteger(priKeyData.substring(512 + 8
                + 512 + 512 + 256, 512 + 8 + 512 + 512 + 256 + 256), 16);
        BigInteger primeExponentP = new BigInteger(priKeyData.substring(512
                + 8 + 512 + 512 + 256 + 256, 512 + 8 + 512 + 512 + 256
                + 256 + 256), 16);
        BigInteger primeExponentQ = new BigInteger(priKeyData.substring(512
                + 8 + 512 + 512 + 256 + 256 + 256, 512 + 8 + 512 + 512
                + 256 + 256 + 256 + 256), 16);
        BigInteger crtCoefficient = new BigInteger(priKeyData.substring(512
                + 8 + 512 + 512 + 256 + 256 + 256 + 256, 512 + 8 + 512
                + 512 + 256 + 256 + 256 + 256 + 256), 16);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPrivateCrtKeySpec rsaPrivateKeySpec = new RSAPrivateCrtKeySpec(
                modulus, publicExponent, privateExponent, primeP, primeQ,
                primeExponentP, primeExponentQ, crtCoefficient);
        return keyFactory.generatePrivate(rsaPrivateKeySpec);
    }
}

Related Tutorials