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

The following examples show how to use java.security.AlgorithmParameters#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: PKCS12KeyStore.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private AlgorithmParameters getAlgorithmParameters(String algorithm)
    throws IOException
{
    AlgorithmParameters algParams = null;

    // create PBE parameters from salt and iteration count
    PBEParameterSpec paramSpec =
            new PBEParameterSpec(getSalt(), iterationCount);
    try {
       algParams = AlgorithmParameters.getInstance(algorithm);
       algParams.init(paramSpec);
    } catch (Exception e) {
       throw new IOException("getAlgorithmParameters failed: " +
                             e.getMessage(), e);
    }
    return algParams;
}
 
Example 2
Source File: PKCS12KeyStore.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private AlgorithmParameters getPBEAlgorithmParameters(String algorithm)
    throws IOException
{
    AlgorithmParameters algParams = null;

    // create PBE parameters from salt and iteration count
    PBEParameterSpec paramSpec =
            new PBEParameterSpec(getSalt(), PBE_ITERATION_COUNT);
    try {
       algParams = AlgorithmParameters.getInstance(algorithm);
       algParams.init(paramSpec);
    } catch (Exception e) {
       throw new IOException("getPBEAlgorithmParameters failed: " +
                             e.getMessage(), e);
    }
    return algParams;
}
 
Example 3
Source File: PKCS12KeyStore.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private AlgorithmParameters getAlgorithmParameters(String algorithm)
    throws IOException
{
    AlgorithmParameters algParams = null;

    // create PBE parameters from salt and iteration count
    PBEParameterSpec paramSpec =
            new PBEParameterSpec(getSalt(), iterationCount);
    try {
       algParams = AlgorithmParameters.getInstance(algorithm);
       algParams.init(paramSpec);
    } catch (Exception e) {
       throw new IOException("getAlgorithmParameters failed: " +
                             e.getMessage(), e);
    }
    return algParams;
}
 
Example 4
Source File: RC2AlgorithmParameters.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] iv_1 = {
            (byte)0x11,(byte)0x11,(byte)0x11,(byte)0x11,
            (byte)0x11,(byte)0x11,(byte)0x11,(byte)0x11,
            (byte)0x33,(byte)0x33
        };

        // check that RC2 is supported by our provider
        AlgorithmParameters rc2Params =
           AlgorithmParameters.getInstance("RC2", "SunJCE");

        // check that getAlgorithm returns "RC2"
        if (!rc2Params.getAlgorithm().equals("RC2")) {
            throw new Exception("getAlgorithm() returned "
                + rc2Params.getAlgorithm() + " instead of RC2");
        }

        // test parameters with effective key size and iv
        byte[] encoded = testParams(rc2Params, new RC2ParameterSpec(2, iv_1));

        // test parameters with just iv
        encoded = testParams(AlgorithmParameters.getInstance("RC2"),
            new RC2ParameterSpec(0, iv_1));

        // test vectors in RFC 2268
        runTests(tests);
    }
 
Example 5
Source File: RC2AlgorithmParameters.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] iv_1 = {
            (byte)0x11,(byte)0x11,(byte)0x11,(byte)0x11,
            (byte)0x11,(byte)0x11,(byte)0x11,(byte)0x11,
            (byte)0x33,(byte)0x33
        };

        // check that RC2 is supported by our provider
        AlgorithmParameters rc2Params =
           AlgorithmParameters.getInstance("RC2", "SunJCE");

        // check that getAlgorithm returns "RC2"
        if (!rc2Params.getAlgorithm().equals("RC2")) {
            throw new Exception("getAlgorithm() returned "
                + rc2Params.getAlgorithm() + " instead of RC2");
        }

        // test parameters with effective key size and iv
        byte[] encoded = testParams(rc2Params, new RC2ParameterSpec(2, iv_1));

        // test parameters with just iv
        encoded = testParams(AlgorithmParameters.getInstance("RC2"),
            new RC2ParameterSpec(0, iv_1));

        // test vectors in RFC 2268
        runTests(tests);
    }
 
Example 6
Source File: TestECDSA2.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private KeyPair genECKeyPair(String curvName, String privD, String pubX,
        String pubY, Provider p) throws Exception {
    AlgorithmParameters params = AlgorithmParameters.getInstance("EC", p);
    params.init(new ECGenParameterSpec(curvName));
    ECParameterSpec ecParams = params.getParameterSpec(ECParameterSpec.class);
    ECPrivateKeySpec privKeySpec =
        new ECPrivateKeySpec(new BigInteger(privD, 16), ecParams);
    ECPublicKeySpec pubKeySpec =
        new ECPublicKeySpec(new ECPoint(new BigInteger(pubX, 16), new BigInteger(pubY, 16)),
                            ecParams);
    PrivateKey privKey = kf.generatePrivate(privKeySpec);
    PublicKey pubKey = kf.generatePublic(pubKeySpec);
    return new KeyPair(pubKey, privKey);
}
 
Example 7
Source File: JDKAlgorithmParameterGenerator.java    From TorrentEngine with GNU General Public License v3.0 5 votes vote down vote up
protected AlgorithmParameters engineGenerateParameters()
     {
         DSAParametersGenerator pGen = new DSAParametersGenerator();

if ( random != null )
{
	pGen.init(strength, 20, random);
}
else
{
	pGen.init(strength, 20, new SecureRandom());
}

         DSAParameters p = pGen.generateParameters();

         AlgorithmParameters params;

         try
         {
             params = AlgorithmParameters.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME);
             params.init(new DSAParameterSpec(p.getP(), p.getQ(), p.getG()));
         }
         catch (Exception e)
         {
             throw new RuntimeException(e.getMessage());
         }

         return params;
     }
 
Example 8
Source File: KeyProtector.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Protects the given cleartext private key, using the password provided at
 * construction time.
 */
byte[] protect(PrivateKey key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = null;
    PBEWithMD5AndTripleDESCipher cipher;
    try {
        sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
        // encrypt private key
        cipher = new PBEWithMD5AndTripleDESCipher();
        cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null);
    } finally {
        pbeKeySpec.clearPassword();
        if (sKey != null) sKey.destroy();
    }
    byte[] plain = key.getEncoded();
    byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length);
    Arrays.fill(plain, (byte)0x00);

    // wrap encrypted private key in EncryptedPrivateKeyInfo
    // (as defined in PKCS#8)
    AlgorithmParameters pbeParams =
        AlgorithmParameters.getInstance("PBE", SunJCE.getInstance());
    pbeParams.init(pbeSpec);

    AlgorithmId encrAlg = new AlgorithmId
        (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams);
    return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded();
}
 
Example 9
Source File: AESEncryption.java    From amazon-cognito-developer-authentication-sample with Apache License 2.0 5 votes vote down vote up
private static byte[] decrypt(byte[] cipherBytes, String key, byte[] iv) {
    try {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        cipher.init(Cipher.DECRYPT_MODE, getKey(key), params);
        return cipher.doFinal(cipherBytes);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Failed to decrypt.", e);
    }
}
 
Example 10
Source File: P11RSAPSSSignatureSpi.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
protected AlgorithmParameters engineGetParameters() {
  if (engineParams == null) {
    if (paramSpec != null) {
      try {
        engineParams = AlgorithmParameters.getInstance("PSS", "BC");
        engineParams.init(paramSpec);
      } catch (Exception ex) {
        throw new IllegalStateException(ex.getMessage(), ex);
      }
    }
  }

  return engineParams;
}
 
Example 11
Source File: EcCurveImpl.java    From protect with MIT License 5 votes vote down vote up
/**
 * Creates an EcCurve from a curve name
 * 
 * @param curveName
 * @return
 * @throws GeneralSecurityException
 */
public static EcCurveImpl createByName(final String curveName) {
	try {
		final AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
		parameters.init(new ECGenParameterSpec(curveName));
		final ECParameterSpec parameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
		return new EcCurveImpl(parameterSpec);
	} catch (GeneralSecurityException e) {
		throw new RuntimeException(e);
	}
}
 
Example 12
Source File: TestECDH2.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private KeyPair genECKeyPair(String curvName, String privD, String pubX,
                             String pubY, Provider p) throws Exception {
    AlgorithmParameters params = AlgorithmParameters.getInstance("EC", p);
    params.init(new ECGenParameterSpec(curvName));
    ECParameterSpec ecParams = params.getParameterSpec(ECParameterSpec.class);
    ECPrivateKeySpec privKeySpec =
        new ECPrivateKeySpec(new BigInteger(privD, 16), ecParams);
    ECPublicKeySpec pubKeySpec =
        new ECPublicKeySpec(new ECPoint(new BigInteger(pubX, 16),
                                        new BigInteger(pubY, 16)),
                            ecParams);
    PrivateKey privKey = kf.generatePrivate(privKeySpec);
    PublicKey pubKey = kf.generatePublic(pubKeySpec);
    return new KeyPair(pubKey, privKey);
}
 
Example 13
Source File: EcUtil.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the ECParameterSpec for a named curve. Not every provider implements the
 * AlgorithmParameters. Therefore, most tests use alternative functions.
 */
public static ECParameterSpec getCurveSpec(String name)
    throws NoSuchAlgorithmException, InvalidParameterSpecException {
  AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
  parameters.init(new ECGenParameterSpec(name));
  return parameters.getParameterSpec(ECParameterSpec.class);
}
 
Example 14
Source File: PKCS12KeyStore.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private AlgorithmParameters parseAlgParameters(ObjectIdentifier algorithm,
    DerInputStream in) throws IOException
{
    AlgorithmParameters algParams = null;
    try {
        DerValue params;
        if (in.available() == 0) {
            params = null;
        } else {
            params = in.getDerValue();
            if (params.tag == DerValue.tag_Null) {
               params = null;
            }
        }
        if (params != null) {
            if (algorithm.equals((Object)pbes2_OID)) {
                algParams = AlgorithmParameters.getInstance("PBES2");
            } else {
                algParams = AlgorithmParameters.getInstance("PBE");
            }
            algParams.init(params.toByteArray());
        }
    } catch (Exception e) {
       throw new IOException("parseAlgParameters failed: " +
                             e.getMessage(), e);
    }
    return algParams;
}
 
Example 15
Source File: ECDH.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ECDHKeySet getSharedSecret (ECKey keyServer, ECKey keyClient) {
        try {

            Security.addProvider(new BouncyCastleProvider());
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC", "SunEC");
            parameters.init(new ECGenParameterSpec("secp256k1"));
            ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
            ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
            ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint()
                    .getYCoord().toBigInteger()), ecParameters);

            KeyFactory kf = KeyFactory.getInstance("EC");
            ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
            ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);

            JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
            JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);

            new ECKey().getKeyCrypter();

            KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");

            aKeyAgree.init(ecPrivKey);
            aKeyAgree.doPhase(ecPubKey, true);

            return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//		MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
//
//		return hash.digest();
    }
 
Example 16
Source File: RC2AlgorithmParameters.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] iv_1 = {
            (byte)0x11,(byte)0x11,(byte)0x11,(byte)0x11,
            (byte)0x11,(byte)0x11,(byte)0x11,(byte)0x11,
            (byte)0x33,(byte)0x33
        };

        // check that RC2 is supported by our provider
        AlgorithmParameters rc2Params =
           AlgorithmParameters.getInstance("RC2", "SunJCE");

        // check that getAlgorithm returns "RC2"
        if (!rc2Params.getAlgorithm().equals("RC2")) {
            throw new Exception("getAlgorithm() returned "
                + rc2Params.getAlgorithm() + " instead of RC2");
        }

        // test parameters with effective key size and iv
        byte[] encoded = testParams(rc2Params, new RC2ParameterSpec(2, iv_1));

        // test parameters with just iv
        encoded = testParams(AlgorithmParameters.getInstance("RC2"),
            new RC2ParameterSpec(0, iv_1));

        // test vectors in RFC 2268
        runTests(tests);
    }
 
Example 17
Source File: CPublicKey.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ECParameterSpec getParams() {
    try {
        AlgorithmParameters ap = AlgorithmParameters.getInstance("EC");
        ap.init(new ECKeySizeParameterSpec(keyLength));
        return ap.getParameterSpec(ECParameterSpec.class);
    } catch (Exception e) {
        throw new ProviderException(e);
    }
}
 
Example 18
Source File: SecurityUtils.java    From RISE-V2G with MIT License 4 votes vote down vote up
/**
 * Checks if the private key is a valid key (according to requirement [V2G2-823]) for the received contract 
 * certificate before saving it to the keystore.
 * @param privateKey The private key corresponding to the contract certificate
 * @param contractCertChain The received contract certificate chain 
 * @return True, if the private key is a valid key, false otherwise.
 */
private static boolean isPrivateKeyValid(ECPrivateKey privateKey, CertificateChainType contractCertChain) {
	AlgorithmParameters parameters;
	
	try {
		parameters = AlgorithmParameters.getInstance("EC");
		parameters.init(new ECGenParameterSpec("secp256r1"));
		
		ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
		
		// Now we need to check if the private key is correct (see requirement [V2G2-823]) 
		BigInteger order = ecParameterSpec.getOrder();
		ECPoint basePoint = ecParameterSpec.getGenerator();
		BigInteger privateKeyValue = privateKey.getS();
		X509Certificate contractCert = getCertificate(contractCertChain.getCertificate());
		ECPublicKey publicKey = (ECPublicKey) contractCert.getPublicKey();
		
		// 1. check
		if (privateKeyValue.compareTo(order) != -1) {
			getLogger().error("Validation of private key failed: its value is not strictly smaller than the "
							+ "order of the base point");
			return false;
		}
		
		// 2. check
		/*
		 * TODO: 
		 * No idea how to check for 
		 * "multiplication of the base point with this value must generate a key matching the public key of 
		 * the contract certificate"
		 * "this value" = value of private key
		 * -> some more expert knowledge on the arithmetic of elliptic curves is needed to tackle this!
		 */
		
	} catch (NoSuchAlgorithmException | InvalidParameterSpecException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
		return false;
	}
	
	return true;
}
 
Example 19
Source File: KeyProtector.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
Key recover(EncryptedPrivateKeyInfo encrInfo)
    throws UnrecoverableKeyException, NoSuchAlgorithmException
{
    byte[] plain;

    try {
        String encrAlg = encrInfo.getAlgorithm().getOID().toString();
        if (!encrAlg.equals(PBE_WITH_MD5_AND_DES3_CBC_OID)
            && !encrAlg.equals(KEY_PROTECTOR_OID)) {
            throw new UnrecoverableKeyException("Unsupported encryption "
                                                + "algorithm");
        }

        if (encrAlg.equals(KEY_PROTECTOR_OID)) {
            // JDK 1.2 style recovery
            plain = recover(encrInfo.getEncryptedData());
        } else {
            byte[] encodedParams =
                encrInfo.getAlgorithm().getEncodedParams();

            // parse the PBE parameters into the corresponding spec
            AlgorithmParameters pbeParams =
                AlgorithmParameters.getInstance("PBE");
            pbeParams.init(encodedParams);
            PBEParameterSpec pbeSpec =
                    pbeParams.getParameterSpec(PBEParameterSpec.class);

            // create PBE key from password
            PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
            SecretKey sKey =
                new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
            pbeKeySpec.clearPassword();

            // decrypt private key
            PBEWithMD5AndTripleDESCipher cipher;
            cipher = new PBEWithMD5AndTripleDESCipher();
            cipher.engineInit(Cipher.DECRYPT_MODE, sKey, pbeSpec, null);
            plain=cipher.engineDoFinal(encrInfo.getEncryptedData(), 0,
                                       encrInfo.getEncryptedData().length);
        }

        // determine the private-key algorithm, and parse private key
        // using the appropriate key factory
        String oidName = new AlgorithmId
            (new PrivateKeyInfo(plain).getAlgorithm().getOID()).getName();
        KeyFactory kFac = KeyFactory.getInstance(oidName);
        return kFac.generatePrivate(new PKCS8EncodedKeySpec(plain));

    } catch (NoSuchAlgorithmException ex) {
        // Note: this catch needed to be here because of the
        // later catch of GeneralSecurityException
        throw ex;
    } catch (IOException ioe) {
        throw new UnrecoverableKeyException(ioe.getMessage());
    } catch (GeneralSecurityException gse) {
        throw new UnrecoverableKeyException(gse.getMessage());
    }
}
 
Example 20
Source File: SupportedGroupsExtension.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
private NamedGroup(int id, NamedGroupType type, String name,
        String oid, String algorithm, boolean isFips,
        ProtocolVersion[] supportedProtocols,
        AlgorithmParameterSpec keAlgParamSpec) {
    this.id = id;
    this.type = type;
    this.name = name;
    this.oid = oid;
    this.algorithm = algorithm;
    this.isFips = isFips;
    this.supportedProtocols = supportedProtocols;
    this.keAlgParamSpec = keAlgParamSpec;

    boolean mediator = (keAlgParamSpec != null);

    // An EC provider, for example the SunEC provider, may support
    // AlgorithmParameters but not KeyPairGenerator or KeyAgreement.
    if (mediator && (type == NamedGroupType.NAMED_GROUP_ECDHE)) {
        mediator = JsseJce.isEcAvailable();
    }
    // Check the specific algorithm parameters.
    if (mediator) {
        try {
            AlgorithmParameters algParams =
                AlgorithmParameters.getInstance(type.algorithm);
            algParams.init(keAlgParamSpec);
        } catch (InvalidParameterSpecException
                | NoSuchAlgorithmException exp) {
            if (type != NamedGroupType.NAMED_GROUP_XDH) {
                mediator = false;
                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
                    SSLLogger.warning(
                        "No AlgorithmParameters for " + name, exp);
                }
            } else {
                // Please remove the following code if the XDH/X25519/X448
                // AlgorithmParameters algorithms are supported in JDK.
                try {
                    KeyAgreement.getInstance(name);

                    // The following service is also needed.  But for
                    // performance, check the KeyAgreement impl only.
                    //
                    // KeyFactory.getInstance(name);
                    // KeyPairGenerator.getInstance(name);
                    // AlgorithmParameters.getInstance(name);
                } catch (NoSuchAlgorithmException nsae) {
                    mediator = false;
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
                        SSLLogger.warning(
                            "No AlgorithmParameters for " + name, nsae);
                    }
                }
            }
        }
    }
    this.isAvailable = mediator;
}