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

The following examples show how to use java.security.AlgorithmParameters#getParameterSpec() . 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: IESCipher.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public void engineInit(
    int opmode,
    Key key,
    AlgorithmParameters params,
    SecureRandom random)
    throws InvalidKeyException, InvalidAlgorithmParameterException
{
    AlgorithmParameterSpec paramSpec = null;

    if (params != null)
    {
        try
        {
            paramSpec = params.getParameterSpec(IESParameterSpec.class);
        }
        catch (Exception e)
        {
            throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString());
        }
    }

    engineParam = params;
    engineInit(opmode, key, paramSpec, random);

}
 
Example 2
Source File: TrailingSignatureAlgorithm.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private ECDSASignatureAlgorithm(ECGenParameterSpec ecSpec, String messageDigestAlgorithm, String hashAndSignAlgorithm) {
    if (!ecSpec.getName().startsWith(SEC_PRIME_FIELD_PREFIX)) {
        throw new IllegalStateException("Non-prime curves are not supported at this time");
    }

    this.ecSpec = ecSpec;
    this.messageDigestAlgorithm = messageDigestAlgorithm;
    this.hashAndSignAlgorithm = hashAndSignAlgorithm;

    try {
        final AlgorithmParameters parameters = AlgorithmParameters.getInstance(ELLIPTIC_CURVE_ALGORITHM);
        parameters.init(ecSpec);
        this.ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
    } catch (NoSuchAlgorithmException | InvalidParameterSpecException e) {
        throw new IllegalStateException("Invalid algorithm", e);
    }
}
 
Example 3
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param publickeybytes
 * @return
 * @throws java.security.spec.InvalidKeySpecException
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.NoSuchProviderException
 * @throws java.security.spec.InvalidParameterSpecException
 */
public static ECPublicKey getUserECPublicKey(byte[] publickeybytes) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException {

    //append the sign byte to the arrays
    byte[] processedXData = new byte[EC_POINTSIZE];
    byte[] processedYData = new byte[EC_POINTSIZE];
    System.arraycopy(publickeybytes, 1, processedXData, 0, EC_POINTSIZE);
    System.arraycopy(publickeybytes, EC_POINTSIZE + 1, processedYData, 0, EC_POINTSIZE);

    ECPoint pubPoint = new ECPoint(new BigInteger(1, processedXData), new BigInteger(1, processedYData));
    AlgorithmParameters params = AlgorithmParameters.getInstance("EC", BC_FIPS_PROVIDER);
    params.init(new ECGenParameterSpec("prime256v1"));
    ECParameterSpec ecParameters = params.getParameterSpec(ECParameterSpec.class);
    ECPublicKeySpec pubECSpec = new ECPublicKeySpec(pubPoint, ecParameters);
    return (ECPublicKey) KeyFactory.getInstance("EC", BC_FIPS_PROVIDER).generatePublic(pubECSpec);
}
 
Example 4
Source File: DSAPrivateKey.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the DSA parameters associated with this key, or null if the
 * parameters could not be parsed.
 */
public DSAParams getParams() {
    try {
        if (algid instanceof DSAParams) {
            return (DSAParams)algid;
        } else {
            DSAParameterSpec paramSpec;
            AlgorithmParameters algParams = algid.getParameters();
            if (algParams == null) {
                return null;
            }
            paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
            return (DSAParams)paramSpec;
        }
    } catch (InvalidParameterSpecException e) {
        return null;
    }
}
 
Example 5
Source File: DSAPrivateKey.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the DSA parameters associated with this key, or null if the
 * parameters could not be parsed.
 */
public DSAParams getParams() {
    try {
        if (algid instanceof DSAParams) {
            return (DSAParams)algid;
        } else {
            DSAParameterSpec paramSpec;
            AlgorithmParameters algParams = algid.getParameters();
            if (algParams == null) {
                return null;
            }
            paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
            return (DSAParams)paramSpec;
        }
    } catch (InvalidParameterSpecException e) {
        return null;
    }
}
 
Example 6
Source File: SupportedGroupsExtension.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
static DHParameterSpec getDHParameterSpec(NamedGroup namedGroup) {
    if (namedGroup.type != NamedGroupType.NAMED_GROUP_FFDHE) {
        throw new RuntimeException(
                "Not a named DH group: " + namedGroup);
    }

    AlgorithmParameters params = namedGroupParams.get(namedGroup);
    if (params == null) {
        throw new RuntimeException(
                "Not a supported DH named group: " + namedGroup);
    }

    try {
        return params.getParameterSpec(DHParameterSpec.class);
    } catch (InvalidParameterSpecException ipse) {
        // should be unlikely
        return getPredefinedDHParameterSpec(namedGroup);
    }
}
 
Example 7
Source File: JsonWebSignatureTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
private PublicKey buildEs256PublicKey(String x, String y)
    throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException {
  AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
  parameters.init(new ECGenParameterSpec("secp256r1"));
  ECPublicKeySpec ecPublicKeySpec =
      new ECPublicKeySpec(
          new ECPoint(
              new BigInteger(1, Base64.decodeBase64(x)),
              new BigInteger(1, Base64.decodeBase64(y))),
          parameters.getParameterSpec(ECParameterSpec.class));
  KeyFactory keyFactory = KeyFactory.getInstance("EC");
  return keyFactory.generatePublic(ecPublicKeySpec);
}
 
Example 8
Source File: EllipticCurvesExtension.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static ECGenParameterSpec getECGenParamSpec(int index) {
    AlgorithmParameters params = idToParams.get(index);
    try {
        return params.getParameterSpec(ECGenParameterSpec.class);
    } catch (InvalidParameterSpecException ipse) {
        // should be unlikely
        String curveOid = getCurveOid(index);
        return new ECGenParameterSpec(curveOid);
    }
}
 
Example 9
Source File: TestAlgParameterGenerator.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkParamStrength(AlgorithmParameters param,
        int strength) throws Exception {
    String algo = param.getAlgorithm();
    if (!algo.equalsIgnoreCase("DSA")) {
        throw new RuntimeException("Unexpected type of parameters: " + algo);
    }
    DSAParameterSpec spec = param.getParameterSpec(DSAParameterSpec.class);
    int valueL = spec.getP().bitLength();
    if (strength != valueL) {
        System.out.println("Expected " + strength + " but actual " + valueL);
        throw new RuntimeException("Wrong P strength");
    }
}
 
Example 10
Source File: CPublicKey.java    From openjdk-jdk8u 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 11
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 12
Source File: TestDSAGenParameterSpec.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void checkParam(AlgorithmParameters param,
        DSAGenParameterSpec genParam) throws InvalidParameterSpecException,
                NoSuchAlgorithmException, NoSuchProviderException,
                InvalidAlgorithmParameterException {
    String algorithm = param.getAlgorithm();
    if (!algorithm.equalsIgnoreCase(ALGORITHM_NAME)) {
        throw new RuntimeException(
                "Unexpected type of parameters: " + algorithm);
    }

    DSAParameterSpec spec = param.getParameterSpec(DSAParameterSpec.class);
    int valueL = spec.getP().bitLength();
    int strengthP = genParam.getPrimePLength();
    if (strengthP != valueL) {
        System.out.printf("P: Expected %d but actual %d%n", strengthP,
                valueL);
        throw new RuntimeException("Wrong P strength");
    }

    int valueN = spec.getQ().bitLength();
    int strengthQ = genParam.getSubprimeQLength();
    if (strengthQ != valueN) {
        System.out.printf("Q: Expected %d but actual %d%n", strengthQ,
                valueN);
        throw new RuntimeException("Wrong Q strength");
    }

    if (genParam.getSubprimeQLength() != genParam.getSeedLength()) {
        System.out.println("Defaut seed length should be the same as Q.");
        throw new RuntimeException("Wrong seed length");
    }

    // use the parameters to generate real DSA keys
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_NAME,
            PROVIDER_NAME);
    keyGen.initialize(spec);
    keyGen.generateKeyPair();
}
 
Example 13
Source File: BrokenJCEBlockCipher.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected void engineInit(
    int                 opmode,
    Key                 key,
    AlgorithmParameters params,
    SecureRandom        random) 
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    AlgorithmParameterSpec  paramSpec = null;

    if (params != null)
    {
        for (int i = 0; i != availableSpecs.length; i++)
        {
            try
            {
                paramSpec = params.getParameterSpec(availableSpecs[i]);
                break;
            }
            catch (Exception e)
            {
                continue;
            }
        }

        if (paramSpec == null)
        {
            throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
        }
    }

    engineParams = params;
    engineInit(opmode, key, paramSpec, random);
}
 
Example 14
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 15
Source File: RC2AlgorithmParameters.java    From jdk8u-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 16
Source File: KeyProtector.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
Key recover(EncryptedPrivateKeyInfo encrInfo)
    throws UnrecoverableKeyException, NoSuchAlgorithmException
{
    byte[] plain = null;
    SecretKey sKey = null;
    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);
            sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES", false);
            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());
    } finally {
        if (plain != null) Arrays.fill(plain, (byte) 0x00);
        if (sKey != null) {
            try {
                sKey.destroy();
            } catch (DestroyFailedException e) {
                //shouldn't happen
            }
        }
    }
}
 
Example 17
Source File: KeyProtector.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
Key recover(EncryptedPrivateKeyInfo encrInfo)
    throws UnrecoverableKeyException, NoSuchAlgorithmException
{
    byte[] plain = null;
    SecretKey sKey = null;
    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);
            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());
    } finally {
        if (plain != null) Arrays.fill(plain, (byte)0x00);
        if (sKey != null) {
            try {
                sKey.destroy();
            } catch (DestroyFailedException e) {
                //shouldn't happen
            }
        }
    }
}
 
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: 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;
}