Java Code Examples for java.security.spec.InvalidKeySpecException

The following examples show how to use java.security.spec.InvalidKeySpecException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
public ElexisEnvironmentLoginDialog(Shell shell, String openidClientSecret, String keycloakUrl,
	String realmPublicKey){
	super(shell);
	
	logger = LoggerFactory.getLogger(getClass());
	
	oauthService = new ServiceBuilder(ElexisEnvironmentLoginContributor.OAUTH2_CLIENT_ID)
		.apiSecret(openidClientSecret).defaultScope("openid").callback(CALLBACK_URL)
		.build(KeycloakApi.instance(keycloakUrl, ElexisEnvironmentLoginContributor.REALM_ID));
	
	KeyFactory kf;
	try {
		kf = KeyFactory.getInstance("RSA");
		X509EncodedKeySpec keySpecX509 =
			new X509EncodedKeySpec(Base64.getDecoder().decode(realmPublicKey));
		RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
		
		jwtParser = Jwts.parserBuilder().setSigningKey(publicKey).build();
	} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
		logger.error("Initialization error", e);
	}
	
}
 
Example 2
Source Project: RipplePower   Source File: KeyFactory.java    License: Apache License 2.0 6 votes vote down vote up
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof X509EncodedKeySpec)
    {
        try
        {
            SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded());
            PublicKey            key = BouncyCastleProvider.getPublicKey(info);

            if (key != null)
            {
                return key;
            }

            throw new InvalidKeySpecException("no factory found for OID: " + info.getAlgorithm().getAlgorithm());
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
 
Example 3
Source Project: openjdk-8   Source File: DESedeKeyFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a <code>SecretKey</code> object from the provided key
 * specification (key material).
 *
 * @param keySpec the specification (key material) of the secret key
 *
 * @return the secret key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected SecretKey engineGenerateSecret(KeySpec keySpec)
    throws InvalidKeySpecException {

    try {
        if (keySpec instanceof DESedeKeySpec) {
            return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
        }
        if (keySpec instanceof SecretKeySpec) {
            return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());

        }
        throw new InvalidKeySpecException
            ("Inappropriate key specification");
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
 
Example 4
/**
 * The key is generating by SecretKeyFactory and its value just copying
 * in the key field of MySecretKey class. So, this is real key derived
 * using the given algo.
 */
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1,
        int iterationCount, int keySize)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    algorithm = algo;
    salt = salt1;
    itereationCount = iterationCount;
    pass = passPhrase;

    PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt,
            iterationCount, keySize);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);

    SecretKey realKey = keyFactory.generateSecret(spec);

    keyLength = realKey.getEncoded().length;

    key = new byte[keyLength];
    System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength);
}
 
Example 5
Source Project: audit4j-core   Source File: EncryptionUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test.
 *
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws UnsupportedEncodingException the unsupported encoding exception
 * @throws InvalidKeySpecException the invalid key spec exception
 */
@Test
public void test() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
	EncryptionUtil util =  EncryptionUtil.getInstance("1234", "abcd");
	String raw = "testRaw";
	try {
		String encrypt = util.encrypt(raw);
		Assert.assertNotNull(encrypt);
		String decrypt = util.decrypt(encrypt);
		Assert.assertNotNull(decrypt);
		Assert.assertEquals(raw, decrypt);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 6
Source Project: nifi   Source File: OpenSSLPKCS5CipherProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, boolean encryptMode)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }

    if (StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException("Encryption with an empty password is not supported");
    }

    validateSalt(encryptionMethod, salt);

    String algorithm = encryptionMethod.getAlgorithm();
    String provider = encryptionMethod.getProvider();

    // Initialize secret key from password
    final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
    final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
    SecretKey tempKey = factory.generateSecret(pbeKeySpec);

    final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, getIterationCount());
    Cipher cipher = Cipher.getInstance(algorithm, provider);
    cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
    return cipher;
}
 
Example 7
Source Project: ripple-lib-java   Source File: KeyFactory.java    License: ISC License 6 votes vote down vote up
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof X509EncodedKeySpec)
    {
        try
        {
            SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded());
            PublicKey            key = BouncyCastleProvider.getPublicKey(info);

            if (key != null)
            {
                return key;
            }

            throw new InvalidKeySpecException("no factory found for OID: " + info.getAlgorithm().getAlgorithm());
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
 
Example 8
Source Project: xipki   Source File: ProxyP11Slot.java    License: Apache License 2.0 6 votes vote down vote up
private PublicKey getPublicKey(P11ObjectIdentifier objectId)
    throws P11UnknownEntityException, P11TokenException {
  ASN1Object req =
      new ProxyMessage.SlotIdAndObjectId(asn1SlotId, new ProxyMessage.ObjectIdentifier(objectId));
  byte[] resp = module.send(P11ProxyConstants.ACTION_GET_PUBLICKEY, req);
  if (resp == null) {
    return null;
  }

  SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfo.getInstance(resp);
  try {
    return KeyUtil.generatePublicKey(pkInfo);
  } catch (InvalidKeySpecException ex) {
    throw new P11TokenException("could not generate Public Key from SubjectPublicKeyInfo:"
        + ex.getMessage(), ex);
  }
}
 
Example 9
Source Project: jdk8u60   Source File: DSAKeyFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example 10
static String generateAesKeyName(Context context)
    throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
  final char[] password = context.getPackageName()
      .toCharArray();

  final byte[] salt = getDeviceSerialNumber(context).getBytes();

  SecretKey key;
  try {
    // what if there's an OS upgrade and now supports the primary
    // PBE
    key = generatePBEKey(password, salt, PRIMARY_PBE_KEY_ALG, ITERATIONS, KEY_SIZE);
  } catch (NoSuchAlgorithmException e) {
    // older devices may not support the have the implementation,
    // try with a weaker algorithm
    key = generatePBEKey(password, salt, BACKUP_PBE_KEY_ALG, ITERATIONS, KEY_SIZE);
  }
  return encode(key.getEncoded());
}
 
Example 11
Source Project: java-docs-samples   Source File: MqttExample.java    License: Apache License 2.0 6 votes vote down vote up
/** Create a Cloud IoT Core JWT for the given project id, signed with the given ES key. */
private static String createJwtEs(String projectId, String privateKeyFile)
    throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("EC");

  return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
 
Example 12
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpec the requested format in which the key material shall be
 * returned
 *
 * @return the underlying key specification (key material) in the
 * requested format
 *
 * @exception InvalidKeySpecException if the requested key
 * specification is inappropriate for the given key, or the
 * given key cannot be processed (e.g., the given key has an
 * unrecognized algorithm or format).
 */
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
    throws InvalidKeySpecException {
    if (key instanceof javax.crypto.interfaces.PBEKey) {
        // Check if requested key spec is amongst the valid ones
        if ((keySpecCl != null)
            && PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            return new PBEKeySpec
                (pKey.getPassword(), pKey.getSalt(),
                 pKey.getIterationCount(), pKey.getEncoded().length*8);
        } else {
            throw new InvalidKeySpecException("Invalid key spec");
        }
    } else {
        throw new InvalidKeySpecException("Invalid key " +
                                           "format/algorithm");
    }
}
 
Example 13
Source Project: Bytecoder   Source File: PBKDF2Core.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpec the requested format in which the key material shall be
 * returned
 *
 * @return the underlying key specification (key material) in the
 * requested format
 *
 * @exception InvalidKeySpecException if the requested key
 * specification is inappropriate for the given key, or the
 * given key cannot be processed (e.g., the given key has an
 * unrecognized algorithm or format).
 */
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
    throws InvalidKeySpecException {
    if (key instanceof javax.crypto.interfaces.PBEKey) {
        // Check if requested key spec is amongst the valid ones
        if ((keySpecCl != null)
            && PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            return new PBEKeySpec
                (pKey.getPassword(), pKey.getSalt(),
                 pKey.getIterationCount(), pKey.getEncoded().length*8);
        } else {
            throw new InvalidKeySpecException("Invalid key spec");
        }
    } else {
        throw new InvalidKeySpecException("Invalid key " +
                                           "format/algorithm");
    }
}
 
Example 14
private KeyPair createKeyPair() throws InvalidKeySpecException, NoSuchAlgorithmException {

        final RSAKeyPairGenerator gen = new RSAKeyPairGenerator();

        gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 80));
        final AsymmetricCipherKeyPair keypair = gen.generateKeyPair();

        final RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic();
        final RSAPrivateCrtKeyParameters privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate();

        final PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(
                new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));

        final PrivateKey privKey = KeyFactory.getInstance("RSA").generatePrivate(
                new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(),
                        privateKey.getExponent(), privateKey.getP(), privateKey.getQ(),
                        privateKey.getDP(), privateKey.getDQ(), privateKey.getQInv()));

        return new KeyPair(pubKey, privKey);
    }
 
Example 15
Source Project: library   Source File: RSAKeyLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads the private key of this process
 *
 * @return the PrivateKey loaded from config/keys/publickey<conf.getProcessId()>
 * @throws Exception problems reading or parsing the key
 */
public PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

        if (defaultKeys) {
            return getPrivateKeyFromString(RSAKeyLoader.DEFAULT_PKEY);
        }

        if (priKey == null) {
                FileReader f = new FileReader(path + "privatekey" + this.id);
                BufferedReader r = new BufferedReader(f);
                String tmp = "";
                String key = "";
                while ((tmp = r.readLine()) != null) {
                        key = key + tmp;
                }
                f.close();
                r.close();
                priKey = getPrivateKeyFromString(key);
        }
        return priKey;
}
 
Example 16
Source Project: AndroidEncryptionExample   Source File: AESEncryptDecrypt.java    License: MIT License 6 votes vote down vote up
/**
 * generates a secret key from the passed in raw key value
 * we create a 256 bit key that is salted using our example
 * salt value above
 *
 * @param key input key in a char array
 * @return a salted key of the type SECRET_KEY_TYPE
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeySpecException
 */
private static SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException,
        UnsupportedEncodingException,
        InvalidKeySpecException,
        NoSuchProviderException
{
    SecretKeyFactory factory = null;
    factory = SecretKeyFactory.getInstance(SECRET_KEY_TYPE,
            SECURITY_PROVIDER);

    KeySpec spec = new PBEKeySpec(key,
            salt.getBytes("UTF-8"),
            ITERATION_COUNT,
            KEY_LENGTH);

    SecretKey tmp = factory.generateSecret(spec);
    return new SecretKeySpec(tmp.getEncoded(), AES);
}
 
Example 17
Source Project: android_9.0.0_r45   Source File: SecureBox.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static PublicKey decodePublicKey(byte[] keyBytes)
        throws NoSuchAlgorithmException, InvalidKeyException {
    BigInteger x =
            new BigInteger(
                    /*signum=*/ 1,
                    Arrays.copyOfRange(keyBytes, 1, 1 + EC_COORDINATE_LEN_BYTES));
    BigInteger y =
            new BigInteger(
                    /*signum=*/ 1,
                    Arrays.copyOfRange(
                            keyBytes, 1 + EC_COORDINATE_LEN_BYTES, EC_PUBLIC_KEY_LEN_BYTES));

    // Checks if the point is indeed on the P-256 curve for security considerations
    validateEcPoint(x, y);

    KeyFactory keyFactory = KeyFactory.getInstance(EC_ALG);
    try {
        return keyFactory.generatePublic(new ECPublicKeySpec(new ECPoint(x, y), EC_PARAM_SPEC));
    } catch (InvalidKeySpecException ex) {
        // This should never happen
        throw new RuntimeException(ex);
    }
}
 
Example 18
Source Project: library   Source File: ServerConnection.java    License: Apache License 2.0 6 votes vote down vote up
/**
* Tulio A. Ribeiro.
* @return SecretKey
*/
   public SecretKey getSecretKey() {
	if (secretKey != null)
		return secretKey;
	else {
		SecretKeyFactory fac;
		PBEKeySpec spec;
		try {
			fac = TOMUtil.getSecretFactory();
			spec = TOMUtil.generateKeySpec(SECRET.toCharArray());
			secretKey = fac.generateSecret(spec);
		} catch (NoSuchAlgorithmException |InvalidKeySpecException e) {
			logger.error("Algorithm error.",e);
		}
	}
	return secretKey;
}
 
Example 19
Source Project: lams   Source File: ExportControlled.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static RSAPublicKey decodeRSAPublicKey(String key) throws RSAException {

        if (key == null) {
            throw ExceptionFactory.createException(RSAException.class, "Key parameter is null");
        }

        int offset = key.indexOf("\n") + 1;
        int len = key.indexOf("-----END PUBLIC KEY-----") - offset;

        // TODO: use standard decoders with Java 6+
        byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return (RSAPublicKey) kf.generatePublic(spec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw ExceptionFactory.createException(RSAException.class, "Unable to decode public key", e);
        }
    }
 
Example 20
Source Project: athenz   Source File: CryptoExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);
    assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);

    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));

    ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
    assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
 
Example 21
Source Project: credhub   Source File: RsaCredentialHelper.java    License: Apache License 2.0 6 votes vote down vote up
public int getKeyLength() {
  final String publicKey = rsaCredentialData.getPublicKey();

  if (StringUtils.isEmpty(publicKey)) {
    return 0;
  }

  try {
    final String key = publicKey
      .replaceFirst(RSA_START, "")
      .replaceFirst(RSA_END, "")
      .replaceAll(NEW_LINE, "");
    final byte[] byteKey = Base64.decodeBase64(key.getBytes(UTF_8));
    final X509EncodedKeySpec x509publicKey = new X509EncodedKeySpec(byteKey);
    final KeyFactory kf = KeyFactory.getInstance("RSA");
    return ((RSAPublicKey) kf.generatePublic(x509publicKey)).getModulus().bitLength();
  } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
    throw new RuntimeException(e);
  }
}
 
Example 22
Source Project: jdk8u_jdk   Source File: DESedeKeyFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a <code>SecretKey</code> object from the provided key
 * specification (key material).
 *
 * @param keySpec the specification (key material) of the secret key
 *
 * @return the secret key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected SecretKey engineGenerateSecret(KeySpec keySpec)
    throws InvalidKeySpecException {

    try {
        if (keySpec instanceof DESedeKeySpec) {
            return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
        }
        if (keySpec instanceof SecretKeySpec) {
            return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());

        }
        throw new InvalidKeySpecException
            ("Inappropriate key specification");
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
 
Example 23
Source Project: nifi   Source File: CipherUtility.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes a {@link Cipher} object with the given PBE parameters.
 *
 * @param algorithm      the algorithm
 * @param provider       the JCA provider
 * @param password       the password
 * @param salt           the salt
 * @param iterationCount the KDF iteration count
 * @param encryptMode    true to encrypt; false to decrypt
 * @return the initialized Cipher
 * @throws IllegalArgumentException if any parameter is invalid
 */
public static Cipher initPBECipher(String algorithm, String provider, String password, byte[] salt, int iterationCount, boolean encryptMode) throws IllegalArgumentException {
    try {
        // Initialize secret key from password
        final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
        SecretKey tempKey = factory.generateSecret(pbeKeySpec);

        final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
        Cipher cipher = Cipher.getInstance(algorithm, provider);
        cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
        return cipher;
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
        throw new IllegalArgumentException("One or more parameters to initialize the PBE cipher were invalid", e);
    }
}
 
Example 24
Source Project: db   Source File: PasswordHash.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Validates a password using a hash.
 *
 * @param password the password to check
 * @param correctHash the hash of the valid password
 * @return true if the password is correct, false if not
 */
public static boolean validatePassword(String password, String correctHash) {
    try {
        return validatePassword(password.toCharArray(), correctHash);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        logger.error("validatePassword failed", ex);
        throw new DbRuntimeException("validatePassword failed", ex);
    }
}
 
Example 25
Source Project: Encryptor4j   Source File: ECDHExportTest.java    License: MIT License 5 votes vote down vote up
/**
 * Loads and returns the elliptic-curve public key from the data byte array.
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 */
public static ECPublicKey loadPublicKey(byte[] data) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException
{
	X9ECParameters params = CustomNamedCurves.getByName("curve25519");
	ECParameterSpec ecParameterSpec = new ECParameterSpec(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed());

	ECPublicKeySpec publicKey = new ECPublicKeySpec(ecParameterSpec.getCurve().decodePoint(data), ecParameterSpec);
	KeyFactory kf = KeyFactory.getInstance("ECDH", "BC");
	return (ECPublicKey) kf.generatePublic(publicKey);
}
 
Example 26
Source Project: jdk8u-dev-jdk   Source File: DESKeyFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Translates a <code>SecretKey</code> object, whose provider may be
 * unknown or potentially untrusted, into a corresponding
 * <code>SecretKey</code> object of this key factory.
 *
 * @param key the key whose provider is unknown or untrusted
 *
 * @return the translated key
 *
 * @exception InvalidKeyException if the given key cannot be processed by
 * this key factory.
 */
protected SecretKey engineTranslateKey(SecretKey key)
    throws InvalidKeyException {

    try {

        if ((key != null) &&
            (key.getAlgorithm().equalsIgnoreCase("DES")) &&
            (key.getFormat().equalsIgnoreCase("RAW"))) {

            // Check if key originates from this factory
            if (key instanceof com.sun.crypto.provider.DESKey) {
                return key;
            }
            // Convert key to spec
            DESKeySpec desKeySpec
                = (DESKeySpec)engineGetKeySpec(key, DESKeySpec.class);
            // Create key from spec, and return it
            return engineGenerateSecret(desKeySpec);

        } else {
            throw new InvalidKeyException
                ("Inappropriate key format/algorithm");
        }

    } catch (InvalidKeySpecException e) {
        throw new InvalidKeyException("Cannot translate key");
    }
}
 
Example 27
Source Project: ripple-lib-java   Source File: KeyFactorySpi.java    License: ISC License 5 votes vote down vote up
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof DSAPrivateKeySpec)
    {
        return new BCDSAPrivateKey((DSAPrivateKeySpec)keySpec);
    }

    return super.engineGeneratePrivate(keySpec);
}
 
Example 28
Source Project: ripple-lib-java   Source File: KeyFactorySpi.java    License: ISC License 5 votes vote down vote up
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof ElGamalPublicKeySpec)
    {
        return new BCElGamalPublicKey((ElGamalPublicKeySpec)keySpec);
    }
    else if (keySpec instanceof DHPublicKeySpec)
    {
        return new BCElGamalPublicKey((DHPublicKeySpec)keySpec);
    }
    return super.engineGeneratePublic(keySpec);
}
 
Example 29
Source Project: mini-platform   Source File: PasswordPBKDF2.java    License: MIT License 5 votes vote down vote up
/**
 * PBKDF2
 * @param password
 * @param salt
 * @return
 */
private String getPbkdf2(String password, String salt) {
    try {
        byte[] bytes = DatatypeConverter.parseHexBinary(salt);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), bytes, iterationCount, keyLength);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
        byte[] hash = secretKeyFactory.generateSecret(spec).getEncoded();
        return DatatypeConverter.printHexBinary(hash);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        return "";
    }
}
 
Example 30
/**
 * Generates a public key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the public key
 *
 * @return the public key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPublicKeySpec) {
            DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keySpec;
            if (SERIAL_INTEROP) {
                return new DSAPublicKey(dsaPubKeySpec.getY(),
                                    dsaPubKeySpec.getP(),
                                    dsaPubKeySpec.getQ(),
                                    dsaPubKeySpec.getG());
            } else {
                return new DSAPublicKeyImpl(dsaPubKeySpec.getY(),
                                    dsaPubKeySpec.getP(),
                                    dsaPubKeySpec.getQ(),
                                    dsaPubKeySpec.getG());
            }
        } else if (keySpec instanceof X509EncodedKeySpec) {
            if (SERIAL_INTEROP) {
                return new DSAPublicKey
                    (((X509EncodedKeySpec)keySpec).getEncoded());
            } else {
                return new DSAPublicKeyImpl
                    (((X509EncodedKeySpec)keySpec).getEncoded());
            }
        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}