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

The following examples show how to use java.security.AlgorithmParameterGenerator#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: TestDSAGenParameterSpec.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void testDSAGenParameterSpec(DataTuple dataTuple)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidParameterSpecException, InvalidAlgorithmParameterException {
    System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
            dataTuple.primePLen, dataTuple.subprimeQLen);

    AlgorithmParameterGenerator apg
            = AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
                    PROVIDER_NAME);

    DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
    // genParamSpec will be null if IllegalAE is thrown when expected.
    if (genParamSpec == null) {
        return;
    }

    try {
        apg.init(genParamSpec, null);
        AlgorithmParameters param = apg.generateParameters();

        checkParam(param, genParamSpec);
        System.out.println("Test case passed");
    } catch (InvalidParameterException ipe) {
        throw new RuntimeException("Test case failed.", ipe);
    }
}
 
Example 2
Source File: TestDSAGenParameterSpec.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void testDSAGenParameterSpec(DataTuple dataTuple)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidParameterSpecException, InvalidAlgorithmParameterException {
    System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
            dataTuple.primePLen, dataTuple.subprimeQLen);

    AlgorithmParameterGenerator apg
            = AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
                    PROVIDER_NAME);

    DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
    // genParamSpec will be null if IllegalAE is thrown when expected.
    if (genParamSpec == null) {
        return;
    }

    try {
        apg.init(genParamSpec, null);
        AlgorithmParameters param = apg.generateParameters();

        checkParam(param, genParamSpec);
        System.out.println("Test case passed");
    } catch (InvalidParameterException ipe) {
        throw new RuntimeException("Test case failed.", ipe);
    }
}
 
Example 3
Source File: TestDSAGenParameterSpec.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void testDSAGenParameterSpec(DataTuple dataTuple)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidParameterSpecException, InvalidAlgorithmParameterException {
    System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
            dataTuple.primePLen, dataTuple.subprimeQLen);

    AlgorithmParameterGenerator apg
            = AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
                    PROVIDER_NAME);

    DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
    // genParamSpec will be null if IllegalAE is thrown when expected.
    if (genParamSpec == null) {
        return;
    }

    try {
        apg.init(genParamSpec, null);
        AlgorithmParameters param = apg.generateParameters();

        checkParam(param, genParamSpec);
        System.out.println("Test case passed");
    } catch (InvalidParameterException ipe) {
        throw new RuntimeException("Test case failed.", ipe);
    }
}
 
Example 4
Source File: TestDSAGenParameterSpec.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void testDSAGenParameterSpec(DataTuple dataTuple)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidParameterSpecException, InvalidAlgorithmParameterException {
    System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
            dataTuple.primePLen, dataTuple.subprimeQLen);

    AlgorithmParameterGenerator apg =
            AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
                    PROVIDER_NAME);

    DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
    // genParamSpec will be null if IllegalAE is thrown when expected.
    if (genParamSpec == null) {
        return;
    }

    try {
        apg.init(genParamSpec, null);
        AlgorithmParameters param = apg.generateParameters();

        checkParam(param, genParamSpec);
        System.out.println("Test case passed");
    } catch (InvalidParameterException ipe) {
        // The DSAGenParameterSpec API support this, but the real
        // implementation in SUN doesn't
        if (!dataTuple.isSunProviderSupported) {
            System.out.println("Test case passed: expected "
                    + "InvalidParameterException is caught");
        } else {
            throw new RuntimeException("Test case failed.", ipe);
        }
    }
}
 
Example 5
Source File: PdfPublicKeySecurityHandler.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) 
    throws IOException,  
           GeneralSecurityException 
{
    
    String s = "1.2.840.113549.3.2";
    
    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    ASN1Primitive derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = 
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (org.bouncycastle.asn1.ASN1Set) null);
    ContentInfo contentinfo = 
        new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();        
}
 
Example 6
Source File: TestDSAGenParameterSpec.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testDSAGenParameterSpec(DataTuple dataTuple)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidParameterSpecException, InvalidAlgorithmParameterException {
    System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
            dataTuple.primePLen, dataTuple.subprimeQLen);

    AlgorithmParameterGenerator apg =
            AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
                    PROVIDER_NAME);

    DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
    // genParamSpec will be null if IllegalAE is thrown when expected.
    if (genParamSpec == null) {
        return;
    }

    try {
        apg.init(genParamSpec, null);
        AlgorithmParameters param = apg.generateParameters();

        checkParam(param, genParamSpec);
        System.out.println("Test case passed");
    } catch (InvalidParameterException ipe) {
        // The DSAGenParameterSpec API support this, but the real
        // implementation in SUN doesn't
        if (!dataTuple.isSunProviderSupported) {
            System.out.println("Test case passed: expected "
                    + "InvalidParameterException is caught");
        } else {
            throw new RuntimeException("Test case failed.", ipe);
        }
    }
}
 
Example 7
Source File: ElGamalTest.java    From java_security with MIT License 4 votes vote down vote up
/**
	 *  
	 *  对于:“Illegal key size or default parameters”异常,是因为美国的出口限制,Sun通过权限文件(local_policy.jar、US_export_policy.jar)做了相应限制。因此存在一些问题:
	 *  Java 6 无政策限制文件:http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html
     *  Java 7 无政策限制文件:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
     *  我的时java7,自己安装的。
     *  /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home/jre/lib/security目录下,对应覆盖local_policy.jar和US_export_policy.jar两个文件。
     *  
     *  切换到%JDK_Home%\jre\lib\security目录下,对应覆盖local_policy.jar和US_export_policy.jar两个文件。同时,你可能有必要在%JRE_Home%\lib\security目录下,也需要对应覆盖这两个文件。
	 */
	
	// jdk实现:“私钥解密、公钥加密” , 对于:“私钥加密、公钥解密”有问题,因为Elgamal不支持
	public static void jdkElgamal()
	{		
		try 
		{
			// 加入对BouncyCastle支持  
			Security.addProvider(new BouncyCastleProvider());
			
			// 1.初始化发送方密钥
			AlgorithmParameterGenerator algorithmParameterGenerator = AlgorithmParameterGenerator.getInstance("Elgamal");
			// 初始化参数生成器
			algorithmParameterGenerator.init(256);
			// 生成算法参数
			AlgorithmParameters algorithmParameters = algorithmParameterGenerator.generateParameters();
			// 构建参数材料
			DHParameterSpec dhParameterSpec = (DHParameterSpec)algorithmParameters.getParameterSpec(DHParameterSpec.class);
			// 实例化密钥生成器
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("Elgamal");	
			// 初始化密钥对生成器  
			keyPairGenerator.initialize(dhParameterSpec, new SecureRandom());
			KeyPair keyPair = keyPairGenerator.generateKeyPair();
			// 公钥
			PublicKey elGamalPublicKey = keyPair.getPublic();
			// 私钥 
			PrivateKey elGamalPrivateKey = keyPair.getPrivate();
			System.out.println("Public Key:" + Base64.encodeBase64String(elGamalPublicKey.getEncoded()));
			System.out.println("Private Key:" + Base64.encodeBase64String(elGamalPrivateKey.getEncoded()));
			
			
			// 2.私钥解密、公钥加密 ---- 加密
			// 初始化公钥  
	        // 密钥材料转换
			X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(elGamalPublicKey.getEncoded());
			// 实例化密钥工厂
			KeyFactory keyFactory2 = KeyFactory.getInstance("Elgamal");
			// 产生公钥
			PublicKey publicKey2 = keyFactory2.generatePublic(x509EncodedKeySpec2);
			// 数据加密 
			// Cipher cipher2 = Cipher.getInstance("Elgamal");
			Cipher cipher2 = Cipher.getInstance(keyFactory2.getAlgorithm()); 
			cipher2.init(Cipher.ENCRYPT_MODE, publicKey2);
			byte[] result2 = cipher2.doFinal(src.getBytes());
			System.out.println("私钥加密、公钥解密 ---- 加密:" + Base64.encodeBase64String(result2));
			
			// 3.私钥解密、公钥加密 ---- 解密
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(elGamalPrivateKey.getEncoded());
			KeyFactory keyFactory5 = KeyFactory.getInstance("Elgamal");
			PrivateKey privateKey5 = keyFactory5.generatePrivate(pkcs8EncodedKeySpec5);
//			Cipher cipher5 = Cipher.getInstance("Elgamal");
			Cipher cipher5 = Cipher.getInstance(keyFactory5.getAlgorithm()); 
			cipher5.init(Cipher.DECRYPT_MODE, privateKey5);
			byte[] result5 = cipher5.doFinal(result2);
			System.out.println("Elgamal 私钥加密、公钥解密 ---- 解密:" + new String(result5));
			
			

			/*	
			// 	私钥加密、公钥解密: 有问题
			// 4.私钥加密、公钥解密 ---- 加密
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(elGamalPrivateKey.getEncoded());
			KeyFactory keyFactory = KeyFactory.getInstance("Elgamal");
			PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
			Cipher cipher = Cipher.getInstance("Elgamal");
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			byte[] result = cipher.doFinal(src.getBytes());
			System.out.println("私钥加密、公钥解密 ---- 加密:" + Base64.encodeBase64String(result));
			
			// 5.私钥加密、公钥解密 ---- 解密
			X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(elGamalPublicKey.getEncoded());
			keyFactory = KeyFactory.getInstance("Elgamal");
			PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
			cipher = Cipher.getInstance("Elgamal");
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			result = cipher.doFinal(result);
			System.out.println("Elgamal 私钥加密、公钥解密 ---- 解密:" + new String(result));
			*/
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}
 
Example 8
Source File: SameDHKeyStressTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static boolean runTest(String algo, int numParties, String secretAlgo) {
    KAParticipant[] parties = new KAParticipant[numParties];
    Key[] keyArchives = new Key[numParties];
    try {
        // generate AlogirhtmParameterSpec
        AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DH","SunJCE");
        AlgorithmParameterSpec aps = new DHGenParameterSpec(512, 64);
        apg.init(aps);
        DHParameterSpec spec = apg.generateParameters().
                getParameterSpec(DHParameterSpec.class);

        //initilize all KeyAgreement participants
        for (int i = 0; i < numParties; i++) {
            parties[i] = new KAParticipant(PA_NAMES[i], algo);
            parties[i].initialize(spec);
            keyArchives[i] = parties[i].getPublicKey();
        }

        // Do all phases in the KeyAgreement for all participants
        Key[] keyBuffer = new Key[numParties];
        boolean lastPhase = false;
        for (int j = 0; j < numParties - 1; j++) {
            if (j == numParties - 2) {
                lastPhase = true;
            }
            for (int k = 0; k < numParties; k++) {
                if (k == numParties - 1) {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[0], lastPhase);
                } else {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[k + 1], lastPhase);
                }
            }
            System.arraycopy(keyBuffer, 0, keyArchives, 0, numParties);
        }

        //Comparison: The secret keys generated by all involved parties should be the same
        SecretKey[] sKeys = new SecretKey[numParties];
        for (int n = 0; n < numParties; n++) {
            sKeys[n] = parties[n].generateSecret(secretAlgo);
        }
        for (int q = 0; q < numParties - 1; q++) {
            if (!Arrays.equals(sKeys[q].getEncoded(), sKeys[q + 1].getEncoded())) {
                return false;
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

}
 
Example 9
Source File: TestAlgParameterGenerator.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    AlgorithmParameterGenerator apg
            = AlgorithmParameterGenerator.getInstance("DSA", "SUN");
    long start, stop;

    // make sure no-init still works
    start = System.currentTimeMillis();
    AlgorithmParameters param = apg.generateParameters();
    stop = System.currentTimeMillis();
    System.out.println("Time: " + (stop - start) + " ms.");

    // make sure the old model works
    int[] strengths = {512, 768, 1024};
    for (int sizeP : strengths) {
        System.out.println("Generating " + sizeP + "-bit DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(sizeP);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, sizeP);
    }

    // now the newer model
    DSAGenParameterSpec[] specSet = {
        new DSAGenParameterSpec(1024, 160),
        new DSAGenParameterSpec(2048, 224),
        new DSAGenParameterSpec(2048, 256)
        // no support for prime size 3072
        // ,new DSAGenParameterSpec(3072, 256)
    };

    for (DSAGenParameterSpec genParam : specSet) {
        System.out.println("Generating (" + genParam.getPrimePLength()
                + ", " + genParam.getSubprimeQLength() + ") DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(genParam, null);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, genParam);
    }
}
 
Example 10
Source File: SameDHKeyStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static boolean runTest(String algo, int numParties, String secretAlgo) {
    KAParticipant[] parties = new KAParticipant[numParties];
    Key[] keyArchives = new Key[numParties];
    try {
        // generate AlogirhtmParameterSpec
        AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DH","SunJCE");
        AlgorithmParameterSpec aps = new DHGenParameterSpec(512, 64);
        apg.init(aps);
        DHParameterSpec spec = apg.generateParameters().
                getParameterSpec(DHParameterSpec.class);

        //initilize all KeyAgreement participants
        for (int i = 0; i < numParties; i++) {
            parties[i] = new KAParticipant(PA_NAMES[i], algo);
            parties[i].initialize(spec);
            keyArchives[i] = parties[i].getPublicKey();
        }

        // Do all phases in the KeyAgreement for all participants
        Key[] keyBuffer = new Key[numParties];
        boolean lastPhase = false;
        for (int j = 0; j < numParties - 1; j++) {
            if (j == numParties - 2) {
                lastPhase = true;
            }
            for (int k = 0; k < numParties; k++) {
                if (k == numParties - 1) {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[0], lastPhase);
                } else {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[k + 1], lastPhase);
                }
            }
            System.arraycopy(keyBuffer, 0, keyArchives, 0, numParties);
        }

        //Comparison: The secret keys generated by all involved parties should be the same
        SecretKey[] sKeys = new SecretKey[numParties];
        for (int n = 0; n < numParties; n++) {
            sKeys[n] = parties[n].generateSecret(secretAlgo);
        }
        for (int q = 0; q < numParties - 1; q++) {
            if (!Arrays.equals(sKeys[q].getEncoded(), sKeys[q + 1].getEncoded())) {
                return false;
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

}
 
Example 11
Source File: TestAlgParameterGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    AlgorithmParameterGenerator apg
            = AlgorithmParameterGenerator.getInstance("DSA", "SUN");
    long start, stop;

    // make sure no-init still works
    start = System.currentTimeMillis();
    AlgorithmParameters param = apg.generateParameters();
    stop = System.currentTimeMillis();
    System.out.println("Time: " + (stop - start) + " ms.");
    checkParamStrength(param, 1024);

    // make sure the old model works
    int[] strengths = {512, 768, 1024};
    for (int sizeP : strengths) {
        System.out.println("Generating " + sizeP + "-bit DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(sizeP);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, sizeP);
    }

    // now the newer model
    DSAGenParameterSpec[] specSet = {
        new DSAGenParameterSpec(1024, 160),
        new DSAGenParameterSpec(2048, 224),
        new DSAGenParameterSpec(2048, 256)
        // no support for prime size 3072
        // ,new DSAGenParameterSpec(3072, 256)
    };

    for (DSAGenParameterSpec genParam : specSet) {
        System.out.println("Generating (" + genParam.getPrimePLength()
                + ", " + genParam.getSubprimeQLength() + ") DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(genParam, null);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, genParam);
    }
}
 
Example 12
Source File: SameDHKeyStressTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static boolean runTest(String algo, int numParties, String secretAlgo) {
    KAParticipant[] parties = new KAParticipant[numParties];
    Key[] keyArchives = new Key[numParties];
    try {
        // generate AlogirhtmParameterSpec
        AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DH","SunJCE");
        AlgorithmParameterSpec aps = new DHGenParameterSpec(512, 64);
        apg.init(aps);
        DHParameterSpec spec = apg.generateParameters().
                getParameterSpec(DHParameterSpec.class);

        //initilize all KeyAgreement participants
        for (int i = 0; i < numParties; i++) {
            parties[i] = new KAParticipant(PA_NAMES[i], algo);
            parties[i].initialize(spec);
            keyArchives[i] = parties[i].getPublicKey();
        }

        // Do all phases in the KeyAgreement for all participants
        Key[] keyBuffer = new Key[numParties];
        boolean lastPhase = false;
        for (int j = 0; j < numParties - 1; j++) {
            if (j == numParties - 2) {
                lastPhase = true;
            }
            for (int k = 0; k < numParties; k++) {
                if (k == numParties - 1) {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[0], lastPhase);
                } else {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[k + 1], lastPhase);
                }
            }
            System.arraycopy(keyBuffer, 0, keyArchives, 0, numParties);
        }

        //Comparison: The secret keys generated by all involved parties should be the same
        SecretKey[] sKeys = new SecretKey[numParties];
        for (int n = 0; n < numParties; n++) {
            sKeys[n] = parties[n].generateSecret(secretAlgo);
        }
        for (int q = 0; q < numParties - 1; q++) {
            if (!Arrays.equals(sKeys[q].getEncoded(), sKeys[q + 1].getEncoded())) {
                return false;
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

}
 
Example 13
Source File: SameDHKeyStressTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static boolean runTest(String algo, int numParties, String secretAlgo) {
    KAParticipant[] parties = new KAParticipant[numParties];
    Key[] keyArchives = new Key[numParties];
    try {
        // generate AlogirhtmParameterSpec
        AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DH","SunJCE");
        AlgorithmParameterSpec aps = new DHGenParameterSpec(512, 64);
        apg.init(aps);
        DHParameterSpec spec = apg.generateParameters().
                getParameterSpec(DHParameterSpec.class);

        //initilize all KeyAgreement participants
        for (int i = 0; i < numParties; i++) {
            parties[i] = new KAParticipant(PA_NAMES[i], algo);
            parties[i].initialize(spec);
            keyArchives[i] = parties[i].getPublicKey();
        }

        // Do all phases in the KeyAgreement for all participants
        Key[] keyBuffer = new Key[numParties];
        boolean lastPhase = false;
        for (int j = 0; j < numParties - 1; j++) {
            if (j == numParties - 2) {
                lastPhase = true;
            }
            for (int k = 0; k < numParties; k++) {
                if (k == numParties - 1) {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[0], lastPhase);
                } else {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[k + 1], lastPhase);
                }
            }
            System.arraycopy(keyBuffer, 0, keyArchives, 0, numParties);
        }

        //Comparison: The secret keys generated by all involved parties should be the same
        SecretKey[] sKeys = new SecretKey[numParties];
        for (int n = 0; n < numParties; n++) {
            sKeys[n] = parties[n].generateSecret(secretAlgo);
        }
        for (int q = 0; q < numParties - 1; q++) {
            if (!Arrays.equals(sKeys[q].getEncoded(), sKeys[q + 1].getEncoded())) {
                return false;
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

}
 
Example 14
Source File: ProviderJcaJceHelper.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
public AlgorithmParameterGenerator createAlgorithmParameterGenerator(String algorithm)
    throws NoSuchAlgorithmException
{
    return AlgorithmParameterGenerator.getInstance(algorithm, provider);
}
 
Example 15
Source File: DefaultJcaJceHelper.java    From ripple-lib-java with ISC License 4 votes vote down vote up
public AlgorithmParameterGenerator createAlgorithmParameterGenerator(String algorithm)
    throws NoSuchAlgorithmException
{
    return AlgorithmParameterGenerator.getInstance(algorithm);
}
 
Example 16
Source File: NamedJcaJceHelper.java    From ripple-lib-java with ISC License 4 votes vote down vote up
public AlgorithmParameterGenerator createAlgorithmParameterGenerator(String algorithm)
    throws NoSuchAlgorithmException, NoSuchProviderException
{
    return AlgorithmParameterGenerator.getInstance(algorithm, providerName);
}
 
Example 17
Source File: TestAlgParameterGenerator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    AlgorithmParameterGenerator apg
            = AlgorithmParameterGenerator.getInstance("DSA", "SUN");
    long start, stop;

    // make sure no-init still works
    start = System.currentTimeMillis();
    AlgorithmParameters param = apg.generateParameters();
    stop = System.currentTimeMillis();
    System.out.println("Time: " + (stop - start) + " ms.");

    // make sure the old model works
    int[] strengths = {512, 768, 1024};
    for (int sizeP : strengths) {
        System.out.println("Generating " + sizeP + "-bit DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(sizeP);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, sizeP);
    }

    // now the newer model
    DSAGenParameterSpec[] specSet = {
        new DSAGenParameterSpec(1024, 160),
        new DSAGenParameterSpec(2048, 224),
        new DSAGenParameterSpec(2048, 256)
        // no support for prime size 3072
        // ,new DSAGenParameterSpec(3072, 256)
    };

    for (DSAGenParameterSpec genParam : specSet) {
        System.out.println("Generating (" + genParam.getPrimePLength()
                + ", " + genParam.getSubprimeQLength() + ") DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(genParam, null);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, genParam);
    }
}
 
Example 18
Source File: SameDHKeyStressTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static boolean runTest(String algo, int numParties, String secretAlgo) {
    KAParticipant[] parties = new KAParticipant[numParties];
    Key[] keyArchives = new Key[numParties];
    try {
        // generate AlogirhtmParameterSpec
        AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DH","SunJCE");
        AlgorithmParameterSpec aps = new DHGenParameterSpec(512, 64);
        apg.init(aps);
        DHParameterSpec spec = apg.generateParameters().
                getParameterSpec(DHParameterSpec.class);

        //initilize all KeyAgreement participants
        for (int i = 0; i < numParties; i++) {
            parties[i] = new KAParticipant(PA_NAMES[i], algo);
            parties[i].initialize(spec);
            keyArchives[i] = parties[i].getPublicKey();
        }

        // Do all phases in the KeyAgreement for all participants
        Key[] keyBuffer = new Key[numParties];
        boolean lastPhase = false;
        for (int j = 0; j < numParties - 1; j++) {
            if (j == numParties - 2) {
                lastPhase = true;
            }
            for (int k = 0; k < numParties; k++) {
                if (k == numParties - 1) {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[0], lastPhase);
                } else {
                    keyBuffer[k] = parties[k].doPhase(keyArchives[k + 1], lastPhase);
                }
            }
            System.arraycopy(keyBuffer, 0, keyArchives, 0, numParties);
        }

        //Comparison: The secret keys generated by all involved parties should be the same
        SecretKey[] sKeys = new SecretKey[numParties];
        for (int n = 0; n < numParties; n++) {
            sKeys[n] = parties[n].generateSecret(secretAlgo);
        }
        for (int q = 0; q < numParties - 1; q++) {
            if (!Arrays.equals(sKeys[q].getEncoded(), sKeys[q + 1].getEncoded())) {
                return false;
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

}
 
Example 19
Source File: TestAlgParameterGenerator.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 {
    AlgorithmParameterGenerator apg
            = AlgorithmParameterGenerator.getInstance("DSA", "SUN");
    long start, stop;

    // make sure no-init still works
    start = System.currentTimeMillis();
    AlgorithmParameters param = apg.generateParameters();
    stop = System.currentTimeMillis();
    System.out.println("Time: " + (stop - start) + " ms.");

    // make sure the old model works
    int[] strengths = {512, 768, 1024};
    for (int sizeP : strengths) {
        System.out.println("Generating " + sizeP + "-bit DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(sizeP);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, sizeP);
    }

    // now the newer model
    DSAGenParameterSpec[] specSet = {
        new DSAGenParameterSpec(1024, 160),
        new DSAGenParameterSpec(2048, 224),
        new DSAGenParameterSpec(2048, 256)
        // no support for prime size 3072
        // ,new DSAGenParameterSpec(3072, 256)
    };

    for (DSAGenParameterSpec genParam : specSet) {
        System.out.println("Generating (" + genParam.getPrimePLength()
                + ", " + genParam.getSubprimeQLength() + ") DSA Parameters");
        start = System.currentTimeMillis();
        apg.init(genParam, null);
        param = apg.generateParameters();
        stop = System.currentTimeMillis();
        System.out.println("Time: " + (stop - start) + " ms.");
        checkParamStrength(param, genParam);
    }
}
 
Example 20
Source File: ToolElGamal.java    From protools with Apache License 2.0 3 votes vote down vote up
/**
 * 生成密钥
 *
 * @return Map 密钥Map
 *
 * @throws Exception
 */
public static Map<String, Object> initKey() throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 实例化算法参数生成器
    AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance(KEY_ALGORITHM);

    // 初始化算法参数生成器
    apg.init(KEY_SIZE);

    // 生成算法参数
    AlgorithmParameters params = apg.generateParameters();

    // 构建参数材料
    DHParameterSpec elParams = params.getParameterSpec(DHParameterSpec.class);

    // 实例化密钥对儿生成器
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM);

    // 初始化密钥对儿生成器
    kpg.initialize(elParams, new SecureRandom());

    // 生成密钥对儿
    KeyPair keys = kpg.genKeyPair();

    // 取得密钥
    PublicKey publicKey = keys.getPublic();

    PrivateKey privateKey = keys.getPrivate();

    // 封装密钥
    Map<String, Object> map = Maps.newHashMapWithExpectedSize(2);

    map.put(PUBLIC_KEY, publicKey);

    map.put(PRIVATE_KEY, privateKey);

    return map;
}