Example usage for java.security.spec RSAKeyGenParameterSpec RSAKeyGenParameterSpec

List of usage examples for java.security.spec RSAKeyGenParameterSpec RSAKeyGenParameterSpec

Introduction

In this page you can find the example usage for java.security.spec RSAKeyGenParameterSpec RSAKeyGenParameterSpec.

Prototype

public RSAKeyGenParameterSpec(int keysize, BigInteger publicExponent) 

Source Link

Document

Constructs a new RSAKeyGenParameterSpec object from the given keysize, public-exponent value, and null key parameters.

Usage

From source file:com.l2jfree.loginserver.manager.LoginManager.java

/**
 * Private constructor to avoid direct instantiation.
 * Initialize a key generator.//from  w w  w.j a  va2  s .c  o  m
 */
private LoginManager() {
    try {
        _log.info("LoginManager: initializing.");

        _hackProtection = new FastMap<InetAddress, FailedLoginAttempt>();

        _keyPairs = new ScrambledKeyPair[10];

        _service = (AccountsServices) L2Registry.getBean("AccountsServices");

        _connections = new FastList<L2Client>();

        KeyPairGenerator keygen = null;

        try {
            keygen = KeyPairGenerator.getInstance("RSA");
            RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
            keygen.initialize(spec);
        } catch (GeneralSecurityException e) {
            _log.fatal("Error in RSA setup:", e);
            _log.info("Server shutting down now");
            System.exit(1);
            return;
        }

        //generate the initial set of keys
        for (int i = 0; i < 10; i++) {
            _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
        }
        _log.info("LoginManager: Cached 10 KeyPairs for RSA communication");

        testCipher((RSAPrivateKey) _keyPairs[0].getPair().getPrivate());

        // Store keys for blowfish communication
        generateBlowFishKeys();
    } catch (GeneralSecurityException e) {
        _log.fatal("FATAL: Failed initializing LoginManager. Reason: " + e.getMessage(), e);
        System.exit(1);
    }

}

From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java

private KeyPair generateKeyPair(int size) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(size, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

From source file:test.be.fedict.eid.applet.RSATest.java

@Test
public void testPSS() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC");

    byte[] data = "hello world".getBytes();

    signature.initSign(privateKey);//from  w  w  w  . j  av a  2s. co m
    signature.update(data);
    byte[] signatureValue = signature.sign();

    LOG.debug("signature size: " + signatureValue.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue)));

    signature.initVerify(publicKey);
    signature.update(data);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    signature.initSign(privateKey);
    signature.update(data);
    byte[] signatureValue2 = signature.sign();

    LOG.debug("signature size: " + signatureValue2.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2)));

    assertFalse(Arrays.equals(signatureValue, signatureValue2));

    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC");
    byte[] digest = messageDigest.digest(data);

    signature = Signature.getInstance("RAWRSASSA-PSS", "BC");
    signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
    signature.initVerify(publicKey);
    signature.update(digest);
    result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java

private KeyPair generateKeyPair() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    return keyPairGenerator.generateKeyPair();
}

From source file:qauth.djd.qauthclient.main.ContentFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Bundle args = getArguments();/*from   www. ja  va 2  s .c o  m*/
    if (args.getCharSequence(KEY_TITLE).toString().equals("Providers")) {

        View rootView = inflater.inflate(R.layout.providers_view_frag, container, false);

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        pAdapter = new ProviderAdapter(pDataset);
        mRecyclerView.setAdapter(pAdapter);

        final PackageManager pm = getActivity().getPackageManager();
        List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

        for (ApplicationInfo packageInfo : packages) {
            //Log.i(TAG, "Installed package :" + packageInfo.packageName);
            //Log.i(TAG, "Source dir : " + packageInfo.sourceDir);
            //Log.i(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));

            if (packageInfo.packageName.equals("qauth.djd.dummyclient")) {
                Provider provider = new Provider("DummyClient", packageInfo.packageName);
                pDataset.add(provider);
                pAdapter.notifyDataSetChanged();
            }

        }

        //get local package names and cross reference with providers on server ("/provider/available")
        //display package names in listview
        //allow user to click on item to activate or deactivate
        // '-> have check box with progress bar indicating status

        return rootView;

    } else {

        View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        wAdapter = new WatchAdapter(wDataset);
        mRecyclerView.setAdapter(wAdapter);

        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
        fab.attachToRecyclerView(mRecyclerView);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("test", "clicked!");

                AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
                builderSingle.setIcon(R.drawable.ic_launcher);
                builderSingle.setTitle("Select Bluetooth Device");
                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                        android.R.layout.select_dialog_singlechoice);
                new Thread(new Runnable() {
                    public void run() {
                        for (String s : getNodes()) {
                            arrayAdapter.add(s);
                        }
                    }
                }).start();
                builderSingle.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String nodeId = arrayAdapter.getItem(which);
                        String privKey = null;
                        String pubKey = null;

                        try {
                            SecureRandom random = new SecureRandom();
                            RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024,
                                    RSAKeyGenParameterSpec.F4);
                            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
                            generator.initialize(spec, random);
                            KeyPair pair = generator.generateKeyPair();
                            privKey = Base64.encodeToString(pair.getPrivate().getEncoded(), Base64.DEFAULT);
                            pubKey = Base64.encodeToString(pair.getPublic().getEncoded(), Base64.DEFAULT);
                        } catch (Exception e) {
                            Log.i("generate", "error: " + e);
                        }

                        //Log.i("keys", "priv key : " + privKey);

                        //String privKey = Base64.encodeToString(MainTabsActivity.privKey.getEncoded(), Base64.DEFAULT);
                        //String pubKey = Base64.encodeToString(MainTabsActivity.pubKey.getEncoded(), Base64.DEFAULT);

                        Keys keys = new Keys(privKey, pubKey);
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        ObjectOutput out = null;
                        try {
                            out = new ObjectOutputStream(bos);
                        } catch (Exception e) {
                        }
                        try {
                            out.writeObject(keys);
                        } catch (Exception e) {
                        }
                        byte b[] = bos.toByteArray();
                        try {
                            out.close();
                        } catch (Exception e) {
                        }
                        try {
                            bos.close();
                        } catch (Exception e) {
                        }

                        Wearable.MessageApi.sendMessage(mGoogleApiClient, nodeId, "REGISTER", b)
                                .setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
                                    @Override
                                    public void onResult(MessageApi.SendMessageResult sendMessageResult) {
                                        if (!sendMessageResult.getStatus().isSuccess()) {
                                            Log.i("MessageApi", "Failed to send message with status code: "
                                                    + sendMessageResult.getStatus().getStatusCode());
                                        } else if (sendMessageResult.getStatus().isSuccess()) {
                                            Log.i("MessageApi", "onResult successful!");
                                        }
                                    }
                                });

                    }
                });
                builderSingle.show();

            }
        });

        mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(
                        new com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener() {
                            @Override
                            public void onConnectionFailed(ConnectionResult result) {
                                Log.i("mGoogleApiClient", "onConnectionFailed: " + result);
                            }
                        })
                // Request access only to the Wearable API
                .addApi(Wearable.API).build();
        mGoogleApiClient.connect();

        /*BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                
        for(BluetoothDevice bt : pairedDevices)
        Log.i("BluetoothDevice", "pairedDevice: " + bt.toString());*/

        return rootView;

    }

}

From source file:net.link.util.common.KeyUtils.java

public static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    SecureRandom random = new SecureRandom();
    if ("RSA".equals(keyPairGenerator.getAlgorithm()))
        try {//w  w  w .  ja v a  2  s  . co m
            keyPairGenerator.initialize(new RSAKeyGenParameterSpec(RSA_KEYSIZE, RSAKeyGenParameterSpec.F4),
                    random);
        } catch (InvalidAlgorithmParameterException e) {
            throw new InternalInconsistencyException("KeyGenParams incompatible with key generator.", e);
        }
    else if (keyPairGenerator instanceof DSAKeyPairGenerator) {
        DSAKeyPairGenerator dsaKeyPairGenerator = (DSAKeyPairGenerator) keyPairGenerator;
        dsaKeyPairGenerator.initialize(DSA_MODLEN, false, random);
    }

    return keyPairGenerator.generateKeyPair();
}

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

private static KeyPair generateKeyPair() throws Exception {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    final SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * Gets the key AlgorithmParameterSpec of supported keys. Can be used to initialize a KeyPairGenerator to generate a key of equal type and size.
 * @param pk PublicKey used to derive the AlgorithmParameterSpec
 * @return null if key is unsupported or pk is null, otherwise a AlgorithmParameterSpec.
 *//*  w  ww  .  jav a  2s  . co  m*/
public static AlgorithmParameterSpec getKeyGenSpec(final PublicKey pk) {
    if (pk == null) {
        return null;
    }
    AlgorithmParameterSpec ret = null;
    if (pk instanceof RSAPublicKey) {
        log.debug("getKeyGenSpec: RSA");
        final RSAPublicKey rpk = (RSAPublicKey) pk;
        ret = new RSAKeyGenParameterSpec(getKeyLength(pk), rpk.getPublicExponent());
    } else if (pk instanceof DSAPublicKey) {
        log.debug("getKeyGenSpec: DSA");
        final DSAPublicKey dpk = (DSAPublicKey) pk;
        final DSAParams params = dpk.getParams();
        ret = new DSAParameterSpec(params.getP(), params.getQ(), params.getG());
    } else if (pk instanceof ECPublicKey) {
        log.debug("getKeyGenSpec: ECPublicKey");
        final ECPublicKey ecpub = (ECPublicKey) pk;
        final java.security.spec.ECParameterSpec sunsp = ecpub.getParams();
        final EllipticCurve ecurve = new EllipticCurve(sunsp.getCurve().getField(), sunsp.getCurve().getA(),
                sunsp.getCurve().getB());
        //ECParameterSpec par = new ECNamedCurveSpec(null, sunsp.getCurve(), sunsp.getGenerator(), sunsp.getOrder(), BigInteger.valueOf(sunsp.getCofactor()));
        final ECParameterSpec params = new ECParameterSpec(ecurve, sunsp.getGenerator(), sunsp.getOrder(),
                sunsp.getCofactor());
        if (log.isDebugEnabled()) {
            log.debug("Fieldsize: " + params.getCurve().getField().getFieldSize());
            final EllipticCurve curve = params.getCurve();
            log.debug("CurveA: " + curve.getA().toString(16));
            log.debug("CurveB: " + curve.getB().toString(16));
            log.debug("CurveSeed: " + curve.getSeed());
            final ECFieldFp field = (ECFieldFp) curve.getField();
            log.debug("CurveSfield: " + field.getP().toString(16));
            final ECPoint p = params.getGenerator();
            log.debug("Generator: " + p.getAffineX().toString(16) + ", " + p.getAffineY().toString(16));
            log.debug("Order: " + params.getOrder().toString(16));
            log.debug("CoFactor: " + params.getCofactor());
        }
        ret = params;
    } else if (pk instanceof JCEECPublicKey) {
        log.debug("getKeyGenSpec: JCEECPublicKey");
        final JCEECPublicKey ecpub = (JCEECPublicKey) pk;
        final org.bouncycastle.jce.spec.ECParameterSpec bcsp = ecpub.getParameters();
        final ECCurve curve = bcsp.getCurve();
        //TODO: this probably does not work for key generation with the Sun PKCS#11 provider. Maybe seed needs to be set to null as above? Or something else, the BC curve is it the same?
        final ECParameterSpec params = new ECNamedCurveSpec(null, curve, bcsp.getG(), bcsp.getN(), bcsp.getH());
        ret = params;
        //EllipticCurve ecc = new EllipticCurve(curve.)
        //ECParameterSpec sp = new ECParameterSpec(, bcsp.getG(), bcsp.getN(), bcsp.getH().intValue());
    }
    return ret;
}

From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

private KeyPair generateKeyPair(int keySize) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Gets the key AlgorithmParameterSpec of supported keys. Can be used to initialize a KeyPairGenerator to generate a key of equal type and size.
 * //from   w  ww.  j  a  va  2 s  .  co m
 * @param pk
 *            PublicKey used to derive the AlgorithmParameterSpec
 * @return null if key is unsupported or pk is null, otherwise a AlgorithmParameterSpec.
 */
public static AlgorithmParameterSpec getKeyGenSpec(final PublicKey pk) {
    if (pk == null) {
        return null;
    }
    AlgorithmParameterSpec ret = null;
    if (pk instanceof RSAPublicKey) {
        log.debug("getKeyGenSpec: RSA");
        final RSAPublicKey rpk = (RSAPublicKey) pk;
        ret = new RSAKeyGenParameterSpec(getKeyLength(pk), rpk.getPublicExponent());
    } else if (pk instanceof DSAPublicKey) {
        log.debug("getKeyGenSpec: DSA");
        final DSAPublicKey dpk = (DSAPublicKey) pk;
        final DSAParams params = dpk.getParams();
        ret = new DSAParameterSpec(params.getP(), params.getQ(), params.getG());
    } else if (pk instanceof ECPublicKey) {
        log.debug("getKeyGenSpec: ECPublicKey");
        final ECPublicKey ecpub = (ECPublicKey) pk;
        final java.security.spec.ECParameterSpec sunsp = ecpub.getParams();
        final EllipticCurve ecurve = new EllipticCurve(sunsp.getCurve().getField(), sunsp.getCurve().getA(),
                sunsp.getCurve().getB());
        // ECParameterSpec par = new ECNamedCurveSpec(null, sunsp.getCurve(), sunsp.getGenerator(), sunsp.getOrder(),
        // BigInteger.valueOf(sunsp.getCofactor()));
        final ECParameterSpec params = new ECParameterSpec(ecurve, sunsp.getGenerator(), sunsp.getOrder(),
                sunsp.getCofactor());
        if (log.isDebugEnabled()) {
            log.debug("Fieldsize: " + params.getCurve().getField().getFieldSize());
            final EllipticCurve curve = params.getCurve();
            log.debug("CurveA: " + curve.getA().toString(16));
            log.debug("CurveB: " + curve.getB().toString(16));
            log.debug("CurveSeed: " + curve.getSeed());
            final ECFieldFp field = (ECFieldFp) curve.getField();
            log.debug("CurveSfield: " + field.getP().toString(16));
            final ECPoint p = params.getGenerator();
            log.debug("Generator: " + p.getAffineX().toString(16) + ", " + p.getAffineY().toString(16));
            log.debug("Order: " + params.getOrder().toString(16));
            log.debug("CoFactor: " + params.getCofactor());
        }
        ret = params;
    } else if (pk instanceof JCEECPublicKey) {
        log.debug("getKeyGenSpec: JCEECPublicKey");
        final JCEECPublicKey ecpub = (JCEECPublicKey) pk;
        final org.bouncycastle.jce.spec.ECParameterSpec bcsp = ecpub.getParameters();
        final ECCurve curve = bcsp.getCurve();
        // TODO: this probably does not work for key generation with the Sun PKCS#11 provider. Maybe seed needs to be set to null as above? Or
        // something else, the BC curve is it the same?
        final ECParameterSpec params = new ECNamedCurveSpec(null, curve, bcsp.getG(), bcsp.getN(), bcsp.getH());
        ret = params;
        // EllipticCurve ecc = new EllipticCurve(curve.)
        // ECParameterSpec sp = new ECParameterSpec(, bcsp.getG(), bcsp.getN(), bcsp.getH().intValue());
    }
    return ret;
}