generate RSA Public Key - Java Security

Java examples for Security:RSA

Description

generate RSA Public Key

Demo Code


//package com.java2s;

import java.math.BigInteger;
import java.security.KeyFactory;

import java.security.PublicKey;

import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class Main {
    public static PublicKey generateRSAPublicKey(String modulus,
            String publicExponent) {
        try {/*from  w w  w. j  av  a2s  . co m*/
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
                    new BigInteger(modulus), new BigInteger(publicExponent));
            return keyFactory.generatePublic(pubKeySpec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static PublicKey generateRSAPublicKey(byte[] key) {
        try {
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePublic(bobPubKeySpec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials