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

The following examples show how to use java.security.KeyPairGenerator#getInstance() . 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: 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 2
Source File: AsymmetricKeyEncryptionClientDemo.java    From markdown-image-kit with MIT License 6 votes vote down vote up
private static void buildAndSaveAsymKeyPair() throws IOException, NoSuchAlgorithmException {
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(1024, srand);
    KeyPair keyPair = keyGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream fos = new FileOutputStream(pubKeyPath);
    fos.write(x509EncodedKeySpec.getEncoded());
    fos.close();

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    fos = new FileOutputStream(priKeyPath);
    fos.write(pkcs8EncodedKeySpec.getEncoded());
    fos.close();
}
 
Example 3
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 4
Source File: GenerateKeypair.java    From TencentKona-8 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 5
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 6
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeysForAPILessThanM(String keyAlias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertificateException, UnrecoverableEntryException, NoSuchPaddingException, KeyStoreException, InvalidKeyException, IOException {
    // Generate a key pair for encryption
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext)
            .setAlias(keyAlias)
            .setSubject(new X500Principal("CN=" + keyAlias))
            .setSerialNumber(BigInteger.TEN)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM_NAME, ANDROID_KEY_STORE_NAME);
    kpg.initialize(spec);
    kpg.generateKeyPair();

    saveEncryptedKey();
}
 
Example 7
Source File: clientUtil.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public KeyPair generatekeys() throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException, InvalidAlgorithmParameterException, InvalidKeyException, SignatureException {

        //generate ECDSA keypair
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA", "BCFIPS");
        ECGenParameterSpec paramSpec = new ECGenParameterSpec(("secp256r1"));

        //initialize
        kpg.initialize(paramSpec, new SecureRandom());
        //generate
        KeyPair keyPair = kpg.generateKeyPair();
        Key priK = (PrivateKey) keyPair.getPrivate();
        return keyPair;
    }
 
Example 8
Source File: Copy.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    KeyPairGenerator kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    KeyPair kp = kg.genKeyPair();

    Signature signature = Signature.getInstance(DSA);
    Test original = new Test();
    SignedObject so = new SignedObject(original, kp.getPrivate(),
            signature);
    System.out.println("Signature algorithm: " + so.getAlgorithm());

    signature = Signature.getInstance(DSA, "SUN");
    if (!so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Verification failed");
    }

    kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    kp = kg.genKeyPair();

    if (so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Unexpected success");
    }

    Object copy = so.getObject();
    if (!original.equals(copy)) {
        throw new RuntimeException("Signed object is not equal "
                + "to original one: " + copy);
    }

    /*
     * The signed object is a copy of an original one.
     * Once the copy is made, further manipulation
     * of the original object shouldn't has any effect on the copy.
     */
    original.set(MAGIC - 1);
    copy = so.getObject();
    if (original.equals(copy)) {
        throw new RuntimeException("Signed object is not a copy "
                + "of original one: " + copy);
    }

    System.out.println("Test passed");
}
 
Example 9
Source File: PrivateKeyEqualityTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeySpecException {
    // Generate the first key.
    KeyPairGenerator generator
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    KeyPair keyPair = generator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
        System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
        throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
    }

    // Generate the second key.
    KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
            rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
    RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
            rsaPrivateKeySpec);

    // Generate the third key.
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
            rsaPrivateKey.getEncoded());
    RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
            encodedKeySpec);

    // Check for equality.
    if (rsaPrivateKey.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
    }
    if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
        throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
    }
    if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
    }
    if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
        throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
    }

    // Generate the fourth key.
    RSAPrivateCrtKey rsaPrivateCrtKey =  (RSAPrivateCrtKey)rsaPrivateKey;
    RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
            rsaPrivateCrtKey.getModulus(),
            rsaPrivateCrtKey.getPublicExponent(),
            rsaPrivateCrtKey.getPrivateExponent(),
            rsaPrivateCrtKey.getPrimeP(),
            rsaPrivateCrtKey.getPrimeQ(),
            rsaPrivateCrtKey.getPrimeExponentP(),
            rsaPrivateCrtKey.getPrimeExponentQ(),
            rsaPrivateCrtKey.getCrtCoefficient()
        );
    RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
            rsaPrivateCrtKeySpec);
    if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
        throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
    }
}
 
Example 10
Source File: SignatureExample.java    From CompetitiveJava with MIT License 4 votes vote down vote up
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
	KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
	KeyPair keyPair = keyPairGen.generateKeyPair();
	return keyPair;
}
 
Example 11
Source File: KeySizeTest.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 {
    int iKeyPairSize = Integer.parseInt(args[0]);
    int maxLoopCnt = Integer.parseInt(args[1]);

    int failCount = 0;
    KeyPairGenerator keyPairGen
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    keyPairGen.initialize(iKeyPairSize);
    // Generate RSA keypair
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // Get priavte and public keys
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    try {
        if (!sizeTest(keyPair)) {
            failCount++;
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }

    for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {

        // Get keysize (modulus) of keys
        KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);

        // Comparing binary length.
        RSAPrivateKeySpec privateKeySpec
                = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
                        RSAPrivateKeySpec.class);
        int iPrivateKeySize = privateKeySpec.getModulus().bitLength();

        RSAPublicKeySpec publicKeySpec
                = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
                        RSAPublicKeySpec.class);
        int iPublicKeySize = publicKeySpec.getModulus().bitLength();

        if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
            System.err.println("iKeyPairSize : " + iKeyPairSize);
            System.err.println("Generated a " + iPrivateKeySize
                    + " bit RSA private key");
            System.err.println("Generated a " + iPublicKeySize
                    + " bit RSA public key");
            failCount++;
        }
    }

    if (failCount > 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}
 
Example 12
Source File: AsymmetricDemo.java    From Hands-On-Cryptography-with-Java with MIT License 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, SignatureException {
    final String original = "Encrypted example from Packt crypto course.";
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair alice = keyPairGenerator.generateKeyPair();
    //In this example, Alice is writing a message to herself. Not to Bob.

    final String cipherName = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
    //Can use other cipher names, like "RSA/ECB/PKCS1Padding"
    Cipher cipher = Cipher.getInstance(cipherName);
    cipher.init(Cipher.ENCRYPT_MODE, alice.getPublic());

    final byte[] originalBytes = original.getBytes(StandardCharsets.UTF_8);
    byte[] cipherTextBytes = cipher.doFinal(originalBytes);

    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initSign(alice.getPrivate());
    sig.update(originalBytes);
    byte[] signatureBytes = sig.sign();
    
    // Decrypt
    cipher.init(Cipher.DECRYPT_MODE, alice.getPrivate());
    byte[] decryptedBytes = cipher.doFinal(cipherTextBytes);
    String decryptedString = new String(decryptedBytes, StandardCharsets.UTF_8);

    System.out.println("Original:\t" + original);
    System.out.println("Encrypted:\t" + Util.bytesToHex(cipherTextBytes));
    System.out.println("Decrypted:\t" + decryptedString);
    if(!decryptedString.equals(original)){
        throw new IllegalArgumentException("Encrypted and decrypted text do not match");
    }
    
    System.out.println("Checking signature...");
    sig.initVerify(alice.getPublic());
    sig.update(decryptedBytes);
    final boolean signatureValid = sig.verify(signatureBytes);
    if(signatureValid){
        System.out.println("Signature checks out; written by key owner.");
    }else{
        throw new IllegalArgumentException("Signature does not match");
    }
}
 
Example 13
Source File: BaseEncryptionManager.java    From samples-android with Apache License 2.0 4 votes vote down vote up
private KeyPairGenerator createKeyPairGenerator() throws GeneralSecurityException {
    return KeyPairGenerator.getInstance(mKeyStoreAlgorithm, mKeyStoreName);
}
 
Example 14
Source File: KeyToolTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Locale reservedLocale = Locale.getDefault();
    try {
        // first test if HumanInputStream really acts like a human being
        HumanInputStream.test();
        KeyToolTest t = new KeyToolTest();

        if (System.getProperty("file") != null) {
            t.sqeTest();
            t.testAll();
            t.i18nTest();
            t.v3extTest("RSA");
            t.v3extTest("DSA");
            boolean testEC = true;
            try {
                KeyPairGenerator.getInstance("EC");
            } catch (NoSuchAlgorithmException nae) {
                testEC = false;
            }
            if (testEC) t.v3extTest("EC");
        }

        if (System.getProperty("nss") != null) {
            t.srcP11Arg = NSS_SRC_P11_ARG;
            t.p11Arg = NSS_P11_ARG;

            t.testPKCS11();

            // FAIL:
            // 1. we still don't have srcprovidername yet
            // 2. cannot store privatekey into NSS keystore
            //    java.security.KeyStoreException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_TEMPLATE_INCOMPLETE.
            //t.testPKCS11ImportKeyStore();

            t.i18nPKCS11Test();
            //FAIL: currently PKCS11-NSS does not support 2 NSS KeyStores to be loaded at the same time
            //t.sszzTest();
        }

        if (System.getProperty("solaris") != null) {
            // For Solaris Cryptography Framework
            t.srcP11Arg = SUN_SRC_P11_ARG;
            t.p11Arg = SUN_P11_ARG;
            t.testPKCS11();
            t.testPKCS11ImportKeyStore();
            t.i18nPKCS11Test();
        }

        System.out.println("Test pass!!!");
    } finally {
        // restore the reserved locale
        Locale.setDefault(reservedLocale);
    }
}
 
Example 15
Source File: RSACrypto.java    From openzaly with Apache License 2.0 4 votes vote down vote up
public static KeyPair buildRSAKeyPair() throws NoSuchAlgorithmException {
	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
	keyPairGenerator.initialize(1024);
	return keyPairGenerator.genKeyPair();
}
 
Example 16
Source File: KeyStoreUtils.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
    public KeyStoreUtils() {
        GuardaApp.getAppComponent().inject(this);

        try {
            keyStore = KeyStore.getInstance(AndroidKeyStore);
            keyStore.load(null);

            if (!keyStore.containsAlias(KEY_ALIAS)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
                    keyGenerator.init(
                            new KeyGenParameterSpec.Builder(KEY_ALIAS,
                                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                                    .setRandomizedEncryptionRequired(false)
                                    .build());
                    keyGenerator.generateKey();
                } else {
                    // 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();
                }
            }

            //Generate and Store AES
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                generateAndStoreAES();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example 17
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 4 votes vote down vote up
private KeyPair RSAKeyPair() throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    return kpg.genKeyPair();
}
 
Example 18
Source File: SignatureTest.java    From protect with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	byte[] data = new byte[20];
	byte[] signature;
	Signature signEng;
	long start, end;

	KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
	kpg.initialize(1024);
	KeyPair kp = kpg.genKeyPair();
	PublicKey publicKey = kp.getPublic();
	PrivateKey privateKey = kp.getPrivate();

	signEng = Signature.getInstance("SHA1withRSA");

	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initSign(privateKey);
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initSign(privateKey);
	}
	end = System.currentTimeMillis();
	System.out.println("1000 init sign: " + (end - start) + "ms");

	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signature = signEng.sign();
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signature = signEng.sign();
	}
	end = System.currentTimeMillis();
	System.out.println("1000 sign: " + (end - start) + "ms");

	signEng.update(data);
	signature = signEng.sign();

	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initVerify(publicKey);
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initVerify(publicKey);
	}
	end = System.currentTimeMillis();
	System.out.println("1000 init verify: " + (end - start) + "ms");

	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signEng.verify(signature);
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signEng.verify(signature);
	}
	end = System.currentTimeMillis();
	System.out.println("1000 verify: " + (end - start) + "ms");
}
 
Example 19
Source File: XMLDSigWithSecMgr.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    URI policyURI =
        new File(System.getProperty("test.src", "."), "policy").toURI();
    Policy.setPolicy
        (Policy.getInstance("JavaPolicy", new URIParameter(policyURI)));
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 20
Source File: TokenUtils.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 2 votes vote down vote up
/**
 * Generate a new RSA keypair.
 *
 * @param keySize - the size of the key
 * @return KeyPair
 * @throws NoSuchAlgorithmException on failure to load RSA key generator
 */
public static KeyPair generateKeyPair(final int keySize) throws NoSuchAlgorithmException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keySize);
    return keyPairGenerator.genKeyPair();
}