All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.dyadicsec.provider.RSAKeyPairGenerator Maven / Gradle / Ivy

Go to download

This is a collection of JAVA libraries that implement Unbound cryptographic classes for JAVA provider, PKCS11 wrapper, cryptoki, and advapi

There is a newer version: 42761
Show newest version
package com.dyadicsec.provider;

import java.security.KeyPair;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidParameterException;
import java.security.KeyPairGeneratorSpi;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.RSAKeyGenParameterSpec;

/**
 * Created by valery.osheter on 19-Apr-16.
 */
public final class RSAKeyPairGenerator extends KeyPairGeneratorSpi
{
    private KeyParameters keyParams = null;
    private int bitSize = 2048;

    @Override
    public void initialize(int bitSize, SecureRandom random)
    {
        this.bitSize = bitSize;
        if (bitSize<2048 || bitSize>4096) throw new InvalidParameterException("Unsupported RSA key size " + bitSize);
    }

    @Override
    public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException
    {
        KeyGenSpec keyGenSpec = null;
        if (params instanceof KeyGenSpec)
        {
            keyGenSpec = (KeyGenSpec) params;
            params = keyGenSpec.original;
            keyParams = keyGenSpec.params;
            if (params==null)
            {
                initialize(keyGenSpec.bitSize, random);
                return;
            }
        }
        if (!(params instanceof RSAKeyGenParameterSpec)) throw new InvalidAlgorithmParameterException("RSAKeyGenParameterSpec required for RSA");
        RSAKeyGenParameterSpec rsaParams = (RSAKeyGenParameterSpec)params;
        initialize(rsaParams.getKeysize(), random);
    }

    @Override
    public KeyPair generateKeyPair()
    {
        RSAPublicKey pubKey = new RSAPublicKey();
        RSAPrivateKey prvKey = null;

        try { prvKey = new RSAPrivateKey().initForGenerate(keyParams, pubKey, bitSize); }
        catch (Exception e) { return null; }

        return new KeyPair(pubKey, prvKey);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy