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

The following examples show how to use java.security.AlgorithmParameters#init() . 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 jdk8u-jdk 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: EllipticCurvesExtension.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example 3
Source File: RC2AlgorithmParameters.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 4
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 5
Source File: PKCS12KeyStore.java    From openjdk-jdk8u-backup 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 6
Source File: RC2AlgorithmParameters.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 7
Source File: PKCS12KeyStore.java    From hottub 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 8
Source File: RC2AlgorithmParameters.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 9
Source File: KeyProtector.java    From Bytecoder with Apache License 2.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", false);
        // 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 10
Source File: SimplePBEByteEncryptor.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
@Override
@SneakyThrows
public byte[] decrypt(byte[] encryptedMessage) {
    int paramsLength = Byte.toUnsignedInt(encryptedMessage[0]);
    int messageLength = encryptedMessage.length - paramsLength - 1;
    byte[] params = new byte[paramsLength];
    byte[] message = new byte[messageLength];
    System.arraycopy(encryptedMessage, 1, params, 0, paramsLength);
    System.arraycopy(encryptedMessage, paramsLength + 1, message, 0, messageLength);

    // create Key
    final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
    final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
    SecretKey key = factory.generateSecret(keySpec);

    // Build parameters
    AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(algorithm);
    algorithmParameters.init(params);

    // Build Cipher
    final Cipher cipherDecrypt = Cipher.getInstance(algorithm);
    cipherDecrypt.init(
            Cipher.DECRYPT_MODE,
            key,
            algorithmParameters
    );


    return cipherDecrypt.doFinal(message);
}
 
Example 11
Source File: CodecUtil.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 生成AES/CBC/PKCS7Padding专用的IV
 * ECB模式只用密钥即可对数据进行加解密,CBC模式需要添加一个参数IV
 * IV是一个16字节的数组,这里采用和IOS一样的构造方法,数据全为0
 */
private static AlgorithmParameters initIV(){
    byte[] iv = new byte[16];
    Arrays.fill(iv, (byte)0x00);
    AlgorithmParameters params;
    try {
        params = AlgorithmParameters.getInstance(ALGORITHM_AES_PKCS7);
        params.init(new IvParameterSpec(iv));
    } catch (Exception e) {
        throw new IllegalArgumentException("生成"+ALGORITHM_CIPHER_AES_PKCS7+"专用的IV时失败", e);
    }
    return params;
}
 
Example 12
Source File: WechatUtil.java    From code with Apache License 2.0 5 votes vote down vote up
public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
    // 被加密的数据
    byte[] dataByte = Base64.decode(encryptedData);
    // 加密秘钥
    byte[] keyByte = Base64.decode(sessionKey);
    // 偏移量
    byte[] ivByte = Base64.decode(iv);
    try {
        // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, "UTF-8");
            return JSON.parseObject(result);
        }
    } catch (Exception e) {
    }
    return null;
}
 
Example 13
Source File: KeyProtector.java    From jdk8u-dev-jdk 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, 20);

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

    // encrypt private key
    PBEWithMD5AndTripleDESCipher cipher;
    cipher = new PBEWithMD5AndTripleDESCipher();
    cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null);
    byte[] plain = key.getEncoded();
    byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length);

    // 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 14
Source File: PKCS12SameKeyId.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }
 
Example 15
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;
}
 
Example 16
Source File: PKCS12SameKeyId.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 {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }
 
Example 17
Source File: AbstractCryptoProvider.java    From oxAuth with MIT License 4 votes vote down vote up
public PublicKey getPublicKey(String alias, JSONObject jwks, Algorithm requestedAlgorithm) throws Exception {
    java.security.PublicKey publicKey = null;

    JSONArray webKeys = jwks.getJSONArray(JSON_WEB_KEY_SET);
    for (int i = 0; i < webKeys.length(); i++) {
        JSONObject key = webKeys.getJSONObject(i);
        if (alias.equals(key.getString(KEY_ID))) {
            AlgorithmFamily family = null;
            if (key.has(ALGORITHM)) {
                Algorithm algorithm = Algorithm.fromString(key.optString(ALGORITHM));

                if (requestedAlgorithm != null && algorithm != requestedAlgorithm) {
                    LOG.trace("kid matched but algorithm does not match. kid algorithm:" + algorithm + ", requestedAlgorithm:" + requestedAlgorithm + ", kid:" + alias);
                    continue;
                }
                family = algorithm.getFamily();
            } else if (key.has(KEY_TYPE)) {
                family = AlgorithmFamily.fromString(key.getString(KEY_TYPE));
            }

            if (AlgorithmFamily.RSA.equals(family)) {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
                        new BigInteger(1, Base64Util.base64urldecode(key.getString(MODULUS))),
                        new BigInteger(1, Base64Util.base64urldecode(key.getString(EXPONENT))));
                publicKey = keyFactory.generatePublic(pubKeySpec);
            } else if (AlgorithmFamily.EC.equals(family)) {
                ECEllipticCurve curve = ECEllipticCurve.fromString(key.optString(CURVE));
                AlgorithmParameters parameters = AlgorithmParameters.getInstance(AlgorithmFamily.EC.toString());
                parameters.init(new ECGenParameterSpec(curve.getAlias()));
                ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);

                publicKey = KeyFactory.getInstance(AlgorithmFamily.EC.toString()).generatePublic(new ECPublicKeySpec(
                        new ECPoint(
                                new BigInteger(1, Base64Util.base64urldecode(key.getString(X))),
                                new BigInteger(1, Base64Util.base64urldecode(key.getString(Y)))
                        ), ecParameters));
            }

            if (key.has(EXPIRATION_TIME)) {
                checkKeyExpiration(alias, key.getLong(EXPIRATION_TIME));
            }
        }
    }

    return publicKey;
}
 
Example 18
Source File: KeyProtector.java    From openjdk-jdk8u-backup 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);
            if (pbeSpec.getIterationCount() > MAX_ITERATION_COUNT) {
                throw new IOException("PBE iteration count too large");
            }

            // 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 19
Source File: KeyProtector.java    From openjdk-8 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: PKCS12SameKeyId.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }