Java Code Examples for java.security.KeyPairGenerator#generateKeyPair()

The following examples show how to use java.security.KeyPairGenerator#generateKeyPair() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RSAUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
/** 
 *  
 * @param keySize 密钥长度 
 * @return return
 */ 
public static Map<String, String> createKeys(int keySize) { 
	// 为RSA算法创建一个KeyPairGenerator对象 
	KeyPairGenerator kpg = null; 
	try { 
		kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM); 
	} catch (NoSuchAlgorithmException e) { 
		e.printStackTrace(); 
	} 

	// 初始化KeyPairGenerator对象,密钥长度 
	kpg.initialize(keySize); 
	// 生成密匙对 
	KeyPair keyPair = kpg.generateKeyPair(); 
	// 得到公钥 
	Key publicKey = keyPair.getPublic(); 
	String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); 
	// 得到私钥 
	Key privateKey = keyPair.getPrivate(); 
	String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); 
	Map<String, String> keys = new HashMap<String, String>(); 
	keys.put("public", publicKeyStr); 
	keys.put("private", privateKeyStr); 
	return keys; 
}
 
Example 2
Source File: GenerateKeypair.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(512);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }

        // test genKeyPair
        kpair = kpg.genKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
Example 3
Source File: CredentialSafe.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Generate a new ES256 keypair (COSE algorithm -7, ECDSA + SHA-256 over the NIST P-256 curve).
 *
 * @param alias The alias used to identify this keypair in the keystore. Needed to use key
 *              in the future.
 * @return The KeyPair object representing the newly generated keypair.
 * @throws VirgilException
 */
private KeyPair generateNewES256KeyPair(String alias) throws VirgilException {
    KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec(CURVE_NAME))
            .setDigests(KeyProperties.DIGEST_SHA256)
            .setUserAuthenticationRequired(this.authenticationRequired) // fingerprint or similar
            .setUserConfirmationRequired(false) // TODO: Decide if we support Android Trusted Confirmations
            .setInvalidatedByBiometricEnrollment(false)
            .setIsStrongBoxBacked(this.strongboxRequired)
            .build();
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE_TYPE);
        keyPairGenerator.initialize(spec);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        throw new VirgilException("couldn't generate key pair: " + e.toString());
    }
}
 
Example 4
Source File: WeEventFileClient.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public void genPemFile(String filePath) throws BrokerException {
    validateLocalFile(filePath);
    try {
        BouncyCastleProvider prov = new BouncyCastleProvider();
        Security.addProvider(prov);

        ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE_TYPE);
        KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM, prov.getName());
        generator.initialize(ecSpec, new SecureRandom());
        KeyPair pair = generator.generateKeyPair();
        String pubKey = pair.getPublic().toString();
        String account = HEX_HEADER + pubKey.substring(pubKey.indexOf("[") + 1, pubKey.indexOf("]")).replace(":", "");

        PemFile privatePemFile = new PemFile(pair.getPrivate(), PRIVATE_KEY_DESC);
        PemFile publicPemFile = new PemFile(pair.getPublic(), PUBLIC_KEY_DESC);


        System.out.println(filePath + PATH_SEPARATOR + account + PRIVATE_KEY_SUFFIX);
        privatePemFile.write(filePath + PATH_SEPARATOR + account + PRIVATE_KEY_SUFFIX);
        publicPemFile.write(filePath + PATH_SEPARATOR + account + PUBLIC_KEY_SUFFIX);
    } catch (IOException | NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        log.error("generate pem file error");
        throw new BrokerException(ErrorCode.FILE_GEN_PEM_BC_FAILED);
    }
}
 
Example 5
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 * <p>
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
    this.provider = provider;

    final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
    final KeyPair keyPair = keyPairGen.generateKeyPair();

    this.privKey = keyPair.getPrivate();

    final PublicKey pubKey = keyPair.getPublic();
    this.publicKey = keyPair.getPublic();
    if (pubKey instanceof BCECPublicKey) {
        pub = ((BCECPublicKey) pubKey).getQ();
    } else if (pubKey instanceof ECPublicKey) {
        pub = extractPublicKey((ECPublicKey) pubKey);
    } else {
        throw new AssertionError(
                "Expected Provider " + provider.getName() +
                        " to produce a subtype of ECPublicKey, found " + pubKey.getClass());
    }
}
 
Example 6
Source File: MainActivity.java    From android-biometricprompt with Apache License 2.0 6 votes vote down vote up
private KeyPair generateKeyPair(String keyName, boolean invalidatedByBiometricEnrollment) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");

    KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
            KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
            .setDigests(KeyProperties.DIGEST_SHA256,
                    KeyProperties.DIGEST_SHA384,
                    KeyProperties.DIGEST_SHA512)
            // Require the user to authenticate with a biometric to authorize every use of the key
            .setUserAuthenticationRequired(true);

    // Generated keys will be invalidated if the biometric templates are added more to user device
    if (Build.VERSION.SDK_INT >= 24) {
        builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
    }

    keyPairGenerator.initialize(builder.build());

    return keyPairGenerator.generateKeyPair();
}
 
Example 7
Source File: KeyStoreUtils.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void generateOldKeyPair() throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
        // Generate the RSA key pairs
        if (!keyStore.containsAlias(KEY_ALIAS)) {
            // Generate a key pair for encryption
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 30);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(KEY_ALIAS)
                    .setSubject(new X500Principal("CN=" + KEY_ALIAS))
                    .setSerialNumber(BigInteger.TEN)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
//            KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", AndroidKeyStore);
            kpg.initialize(spec);
            kpg.generateKeyPair();
        }
    }
 
Example 8
Source File: GenerateKeysExample.java    From jlibra with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Ed25519", "BC");
    KeyPair keyPair = kpGen.generateKeyPair();

    BCEdDSAPrivateKey privateKey = (BCEdDSAPrivateKey) keyPair.getPrivate();

    BCEdDSAPublicKey publicKey = (BCEdDSAPublicKey) keyPair.getPublic();

    AuthenticationKey authenticationKey = AuthenticationKey.fromPublicKey(publicKey);
    logger.info("Libra address: {}",
            AccountAddress.fromAuthenticationKey(authenticationKey));
    logger.info("Authentication key: {}", authenticationKey);
    logger.info("Public key: {}", ByteArray.from(publicKey.getEncoded()));
    logger.info("Private key: {}", ByteArray.from(privateKey.getEncoded()));
}
 
Example 9
Source File: ECKeyGenerator.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public KeyPair generate() {
    // obtain an EC key pair generator for the specified named curve
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(EC_KEY_GEN_ALGORITHM);
        ECGenParameterSpec ecName = new ECGenParameterSpec(namedCurve);
        generator.initialize(ecName);
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        throw new KeyGeneratorException("Unable to generate EC public/private key pair using named curve: " + namedCurve, e);
    }

    return generator.generateKeyPair();
}
 
Example 10
Source File: RSAEncryptDecrypt.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        KeyPairGenerator generator =
            KeyPairGenerator.getInstance("RSA", "SunMSCAPI");

        KeyPair keyPair = generator.generateKeyPair();
        Key publicKey = keyPair.getPublic();
        Key privateKey = keyPair.getPrivate();

        Cipher cipher = null;

        try {
            cipher = Cipher.getInstance("RSA", "SunMSCAPI");

        } catch (GeneralSecurityException e) {
            System.out.println("Cipher not supported by provider, skipping...");
            return;
        }

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        displayBytes("Plaintext data:", PLAINTEXT);
        byte[] data = cipher.doFinal(PLAINTEXT);
        displayBytes("Encrypted data:", data);

        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        data = cipher.doFinal(data);
        displayBytes("Decrypted data:", data);
    }
 
Example 11
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generates a RSA public/private key pair to encrypt AES key
 * @param context
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeyPair(Context context) throws KeyStoreException,
        CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException,
        InvalidAlgorithmParameterException {

    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
    keyStore.load(null);

    if (!keyStore.containsAlias(KEY_ALIAS_AMAZE)) {
        // generate a RSA key pair to encrypt/decrypt AES key from preferences
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 30);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", KEY_STORE_ANDROID);

        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(KEY_ALIAS_AMAZE)
                .setSubject(new X500Principal("CN=" + KEY_ALIAS_AMAZE))
                .setSerialNumber(BigInteger.TEN)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();

        keyPairGenerator.initialize(spec);
        keyPairGenerator.generateKeyPair();
    }
}
 
Example 12
Source File: RSAUtils.java    From NetworkDisk_Storage with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * 生成密钥对(公钥和私钥)
 * </p>
 * 
 * @return
 * @throws Exception
 */
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}
 
Example 13
Source File: RSAKeyGenerator.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public KeyPair generate() {
    // obtain an RSA key pair generator for the specified key size
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(RSA_KEY_GEN_ALGORITHM);
        generator.initialize(keySize);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyGeneratorException("Unable to generate " + keySize + "-bit RSA public/private key pair", e);
    }

    return generator.generateKeyPair();
}
 
Example 14
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
  
  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 
  
  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
 
  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
  
  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);
  
  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
 
Example 15
Source File: PFSecurityUtilsOld.java    From PFLockScreen-Android with Apache License 2.0 5 votes vote down vote up
private boolean generateKeyOld(
        Context context,
        String keystoreAlias,
        boolean isAuthenticationRequired
) {
    try {
        final Calendar start = Calendar.getInstance();
        final Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 25);

        final KeyPairGenerator keyGen = KeyPairGenerator
                .getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");

        final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(keystoreAlias)
                .setSubject(new X500Principal("CN=" + keystoreAlias))
                .setSerialNumber(BigInteger.valueOf(Math.abs(keystoreAlias.hashCode())))
                .setEndDate(end.getTime())
                .setStartDate(start.getTime())
                .setSerialNumber(BigInteger.ONE)
                .setSubject(new X500Principal(
                        "CN = Secured Preference Store, O = Devliving Online")
                )
                .build();

        keyGen.initialize(spec);
        keyGen.generateKeyPair();
        return true;

    } catch ( NoSuchAlgorithmException
            | NoSuchProviderException
            | InvalidAlgorithmParameterException exc) {
        exc.printStackTrace();
        return false;
    }
}
 
Example 16
Source File: TestKeyOpts.java    From julongchain with Apache License 2.0 4 votes vote down vote up
@Test
public void test2() {

	try {

		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(2048);
		KeyPair key = keyGen.generateKeyPair();

		PKCS11KeyData keyraw = new PKCS11KeyData();
		keyraw.setRawPri(key.getPrivate().getEncoded());
		keyraw.setRawPub(key.getPublic().getEncoded());

		IKeyImportOpts opts = new RsaOpts.RSAPrivateKeyImportOpts(false);
		IKey mykey = csp.keyImport(keyraw, opts);
		Assert.assertNotNull(mykey);

		String input2 = "Hello world !TOM";
		PKCS11HashOpts.SHA1Opts hashopt_sha1 = new PKCS11HashOpts.SHA1Opts();
		byte[] bytehash = csp.hash(input2.getBytes(), hashopt_sha1);
		Assert.assertNotNull(bytehash);

		Signature signature = Signature.getInstance("SHA1withRSA");
		signature.initSign(key.getPrivate());
		signature.update(bytehash);
		byte[] signvalue1 = signature.sign();
		Assert.assertNotNull(signvalue1);

		byte[] signvalue = csp.sign(mykey, bytehash, RsaSignOpts.SHA1);
		Assert.assertNotNull(signvalue);

		boolean bverify = csp.verify(mykey, signvalue, bytehash, RsaSignOpts.SHA1);
		Assert.assertNotNull(bverify);

		signature.initVerify(key.getPublic());
		signature.update(bytehash);
		boolean bverify1 = signature.verify(signvalue);
		Assert.assertTrue(bverify1);

	} catch (JulongChainException | InvalidKeyException |NoSuchAlgorithmException| SignatureException e) {
		e.printStackTrace();
	}
}
 
Example 17
Source File: SignatureLength.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static void main0(String keyAlgorithm, int keysize,
        String signatureAlgorithm, Provider generatorProvider,
        Provider signerProvider, Provider verifierProvider,
        boolean mayNotThrow) throws Exception {

    KeyPairGenerator generator;
    Signature signer;
    Signature verifier;

    try {
        generator = KeyPairGenerator.getInstance(keyAlgorithm,
                generatorProvider);
        signer = Signature.getInstance(signatureAlgorithm,
                signerProvider);
        verifier = Signature.getInstance(signatureAlgorithm,
                verifierProvider);
    } catch (NoSuchAlgorithmException nsae) {
        // ignore this set of providers
        return;
    }

    byte[] plaintext = "aaa".getBytes("UTF-8");

    // Generate
    generator.initialize(keysize);
    System.out.println("Generating " + keyAlgorithm + " keypair using " +
        generator.getProvider().getName() + " JCE provider");
    KeyPair keypair = generator.generateKeyPair();

    // Sign
    signer.initSign(keypair.getPrivate());
    signer.update(plaintext);
    System.out.println("Signing using " + signer.getProvider().getName() +
        " JCE provider");
    byte[] signature = signer.sign();

    // Invalidate
    System.out.println("Invalidating signature ...");
    byte[] badSignature = new byte[signature.length + 5];
    System.arraycopy(signature, 0, badSignature, 0, signature.length);
    badSignature[signature.length] = 0x01;
    badSignature[signature.length + 1] = 0x01;
    badSignature[signature.length + 2] = 0x01;
    badSignature[signature.length + 3] = 0x01;
    badSignature[signature.length + 4] = 0x01;

    // Verify
    verifier.initVerify(keypair.getPublic());
    verifier.update(plaintext);
    System.out.println("Verifying using " +
        verifier.getProvider().getName() + " JCE provider");

    try {
        boolean valid = verifier.verify(badSignature);
        System.out.println("Valid? " + valid);
        if (mayNotThrow) {
            if (valid) {
                throw new Exception(
                    "ERROR: expected a SignatureException but none was thrown"
                    + " and invalid signature was verified");
            } else {
                System.out.println("OK: verification failed as expected");
            }
        } else {
            throw new Exception(
                "ERROR: expected a SignatureException but none was thrown");
        }
    } catch (SignatureException e) {
        System.out.println("OK: caught expected exception: " + e);
    }
    System.out.println();
}
 
Example 18
Source File: PKCS10AttrEncoding.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // initializations
        int len = ids.length;
        Object[] values = {
            new ObjectIdentifier("1.2.3.4"),
            new GregorianCalendar(1970, 1, 25, 8, 56, 7).getTime(),
            "challenging"
        };
        for (int j = 0; j < len; j++) {
            constructedMap.put(ids[j], values[j]);
        }

        X500Name subject = new X500Name("cn=Test");
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        String sigAlg = "DSA";

        keyGen.initialize(512);

        KeyPair pair = keyGen.generateKeyPair();
        X509Key publicKey = (X509Key) pair.getPublic();
        PrivateKey privateKey = pair.getPrivate();

        Signature signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);

        // Create the PKCS10 request
        PKCS10Attribute[] attrs = new PKCS10Attribute[len];
        for (int j = 0; j < len; j++) {
            attrs[j] = new PKCS10Attribute(ids[j], values[j]);
        }
        PKCS10 req = new PKCS10(publicKey, new PKCS10Attributes(attrs));
        System.out.println("List of attributes in constructed PKCS10 "
                + "request: ");
        checkAttributes(req.getAttributes().getElements());

        // Encode the PKCS10 request and generate another PKCS10 request from
        // the encoded byte array
        req.encodeAndSign(subject, signature);
        PKCS10 resp = new PKCS10(req.getEncoded());
        System.out.println("List of attributes in DER encoded PKCS10 Request:");
        checkAttributes(resp.getAttributes().getElements());

        if (failedCount > 0) {
            throw new RuntimeException("Attributes Compared : Failed");
        }
        System.out.println("Attributes Compared : Pass");
    }
 
Example 19
Source File: TestOAEPPadding.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    cp = Security.getProvider("SunJCE");
    System.out.println("Testing provider " + cp.getName() + "...");
    Provider kfp = Security.getProvider("SunRsaSign");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", kfp);
    kpg.initialize(2048);
    KeyPair kp = kpg.generateKeyPair();
    privateKey = (RSAPrivateKey)kp.getPrivate();
    publicKey = (RSAPublicKey)kp.getPublic();

    // Test using a spec with each digest algorithm case
    // MD5
    test(new OAEPParameterSpec("MD5", "MGF1",
            MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1",
            MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1",
            MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1",
            MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1",
            MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA1
    test(new OAEPParameterSpec("SHA1", "MGF1",
            MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1",
            MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1",
            MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1",
            MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1",
            MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // For default OAEPParameterSpec case (SHA1)
    test(null);
    // SHA-224
    test(new OAEPParameterSpec("SHA-224", "MGF1",
            MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1",
            MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1",
            MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1",
            MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1",
            MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA-256
    test(new OAEPParameterSpec("SHA-256", "MGF1",
            MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1",
            MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1",
            MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1",
            MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1",
            MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA-384
    test(new OAEPParameterSpec("SHA-384", "MGF1",
            MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1",
            MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1",
            MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1",
            MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1",
            MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA-512
    test(new OAEPParameterSpec("SHA-512", "MGF1",
            MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1",
            MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1",
            MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1",
            MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1",
            MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA-512/224 and SHA-512/256
    test(new OAEPParameterSpec("SHA-512/224", "MGF1",
            MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512/224", "MGF1",
            MGF1ParameterSpec.SHA512_224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512/256", "MGF1",
            MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512/256", "MGF1",
            MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));

    if (failed) {
        throw new Exception("Test failed");
    }
}
 
Example 20
Source File: KeyGeneratorCli.java    From protect with MIT License 4 votes vote down vote up
public static void main(String[] args) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, CertificateEncodingException {

		Security.addProvider(new BouncyCastleProvider());
		Security.addProvider(new EdDSASecurityProvider());

		// Check usage
		if (args.length < 2) {
			System.err.println("USAGE: key-path key-name");
			System.exit(1);
		}
		final File keyPath = new File(args[0]);
		final String keyName = args[1];

		// Generate EC Key Pair
		final KeyPair tlsKeyPair = EcKeyGeneration.generateKeyPair();

		// Generate Ed25519 Key Pair
		final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(EdDSASecurityProvider.PROVIDER_NAME);
		final KeyPair signingKeyPair = keyGen.generateKeyPair();

		// Generate Paillier Key Pair
		final PaillierKeyGenerator encryptionKeyGenerator = new PaillierKeyGenerator(2048);
		final PaillierKeyPair paillierKeyPair = encryptionKeyGenerator.generate();
		final KeyPair encryptionKeyPair = convertFromPaillier(paillierKeyPair);

		// Write public keys
		final File publicKeyFile = new File(keyPath, "public-" + keyName);
		try (PemWriter writer = new PemWriter(new FileWriter(publicKeyFile.getAbsolutePath()))) {
			Pem.writeObject(tlsKeyPair.getPublic(), writer);
			Pem.writeObject(signingKeyPair.getPublic(), writer);
			Pem.writeObject(encryptionKeyPair.getPublic(), writer);
		}
		System.out.println("Wrote: " + publicKeyFile.getAbsolutePath());
		try (final BufferedReader reader = new BufferedReader(new FileReader(publicKeyFile));) {
			String line;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		}

		// Write private keys
		final File privateKeyFile = new File(keyPath, "private-" + keyName);
		try (PemWriter writer = new PemWriter(new FileWriter(privateKeyFile.getAbsolutePath()))) {
			Pem.writeObject(tlsKeyPair.getPrivate(), writer);
			Pem.writeObject(signingKeyPair.getPrivate(), writer);
			Pem.writeObject(encryptionKeyPair.getPrivate(), writer);
		}
		System.out.println("Wrote: " + privateKeyFile.getAbsolutePath());
	}