java.security.spec.InvalidKeySpecException Java Examples

The following examples show how to use java.security.spec.InvalidKeySpecException. 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: SslClientCertificateImplTest.java    From hivemq-community-edition with Apache License 2.0 7 votes vote down vote up
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 #2
Source File: PBKDF2Core.java    From Bytecoder with 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 #3
Source File: ServerConnection.java    From library with 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 #4
Source File: DESedeKeyFactory.java    From jdk8u_jdk with 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 #5
Source File: DESedeKeyFactory.java    From openjdk-8 with 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 #6
Source File: CryptoExceptionTest.java    From athenz with 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 #7
Source File: KeyFactory.java    From RipplePower with 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 #8
Source File: ElexisEnvironmentLoginDialog.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
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 #9
Source File: RsaCredentialHelper.java    From credhub with 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 #10
Source File: ExportControlled.java    From lams with 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 #11
Source File: PBKDF2TranslateTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #12
Source File: SecureBox.java    From android_9.0.0_r45 with 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 #13
Source File: OpenSSLPKCS5CipherProvider.java    From nifi with 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 #14
Source File: KeyFactory.java    From ripple-lib-java with 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 #15
Source File: AESEncryptDecrypt.java    From AndroidEncryptionExample with 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 #16
Source File: ProxyP11Slot.java    From xipki with 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 #17
Source File: DSAKeyFactory.java    From jdk8u60 with 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 #18
Source File: RSAKeyLoader.java    From library with 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 #19
Source File: SecureCoderDecoder.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
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 #20
Source File: MqttExample.java    From java-docs-samples with 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 #21
Source File: EncryptionUtilTest.java    From audit4j-core with 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 #22
Source File: PBKDF2HmacSHA1Factory.java    From jdk8u-jdk with GNU General Public License v2.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 #23
Source File: CipherUtility.java    From nifi with 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 File: XMLHelpers.java    From SAMLRaider with MIT License 5 votes vote down vote up
/**
 * Sign assertions in SAML message
 *
 * @param document
 *            Document in assertions should be signed
 * @param signAlgorithm
 *            Signature algorithm in uri form, default if an unknown
 *            algorithm is provided:
 *            http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * @param digestAlgorithm
 *            Digest algorithm in uri form, default if an unknown algorithm
 *            is provided: http://www.w3.org/2001/04/xmlenc#sha256
 */
public void signAssertion(Document document, String signAlgorithm, String digestAlgorithm, X509Certificate cert, PrivateKey key)
		throws CertificateException, FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
		MarshalException, XMLSignatureException, IOException {
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		setIDAttribute(document);
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile("//*[local-name()='Assertion']/@ID");
		NodeList nlURIs = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

		String[] sigIDs = new String[nlURIs.getLength()];

		for (int i = 0; i < nlURIs.getLength(); i++) {
			sigIDs[i] = nlURIs.item(i).getNodeValue();
		}

		Init.init();
		for (String id : sigIDs) {
			signElement(document, id, cert, key, signAlgorithm, digestAlgorithm);
		}
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example #25
Source File: KeyStoreServiceTest.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadPemFile() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, CertificateException, KeyStoreException {
    PEMManager pemManager = new PEMManager();
    // need pem
    InputStream nodeCrtInput = new ClassPathResource("test.pem").getInputStream();
    pemManager.load(nodeCrtInput);
    System.out.println(pemManager.getPrivateKey());
    System.out.println(Numeric.toHexString(pemManager.getPrivateKey().getEncoded()));
}
 
Example #26
Source File: PBMacDoFinalVsUpdate.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get SecretKey for the given PBKDF2 algorithm.
 *
 * @param thePBKDF2Algorithm - PBKDF2 algorithm
 * @return SecretKey according to thePBKDF2Algorithm
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
protected SecretKey getSecretKey(String thePBKDF2Algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Prepare salt
    byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation
    new SecureRandom().nextBytes(salt);

    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(
            "A #pwd# implied to be hidden!".toCharArray(),
            salt, 1000, 128);
    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(thePBKDF2Algorithm);
    return keyFactory.generateSecret(pbeKeySpec);
}
 
Example #27
Source File: TransactionId.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static TransactionId sha1TransactionId(SubjectPublicKeyInfo spki)
    throws InvalidKeySpecException {
  Args.notNull(spki, "spki");

  byte[] encoded;
  try {
    encoded = spki.getEncoded();
  } catch (IOException ex) {
    throw new InvalidKeySpecException("IOException while ");
  }

  return sha1TransactionId(encoded);
}
 
Example #28
Source File: KeyFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a specification (key material) of the given key object.
 * {@code keySpec} identifies the specification class in which
 * the key material should be returned. It could, for example, be
 * {@code DSAPublicKeySpec.class}, to indicate that the
 * key material should be returned in an instance of the
 * {@code DSAPublicKeySpec} class.
 *
 * @param <T> the type of the key specification to be returned
 *
 * @param key the key.
 *
 * @param keySpec the specification class in which
 * the key material should be returned.
 *
 * @return the underlying key specification (key material) in an instance
 * of the requested specification class.
 *
 * @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).
 */
public final <T extends KeySpec> T getKeySpec(Key key, Class<T> keySpec)
        throws InvalidKeySpecException {
    if (serviceIterator == null) {
        return spi.engineGetKeySpec(key, keySpec);
    }
    Exception failure = null;
    KeyFactorySpi mySpi = spi;
    do {
        try {
            return mySpi.engineGetKeySpec(key, keySpec);
        } catch (Exception e) {
            if (failure == null) {
                failure = e;
            }
            mySpi = nextSpi(mySpi);
        }
    } while (mySpi != null);
    if (failure instanceof RuntimeException) {
        throw (RuntimeException)failure;
    }
    if (failure instanceof InvalidKeySpecException) {
        throw (InvalidKeySpecException)failure;
    }
    throw new InvalidKeySpecException
            ("Could not get key spec", failure);
}
 
Example #29
Source File: ECDHExportTest.java    From Encryptor4j with 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 #30
Source File: SecurityTest.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
@Test
public void generatePublicKeyIllegalArgumentException()
        throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException {

    Logger logger = new DiscardLogger();
    String base64PublicKey = "base64PublicKey";
    String signedData = "signedData";
    String signature = "signature";

    for (Security s : mSecurities) {
        doThrow(new IllegalArgumentException()).when(s).generatePublicKey(base64PublicKey);
        assertThat(s.verifyPurchase(logger, base64PublicKey, signedData, signature)).isFalse();
        verify(s).generatePublicKey(base64PublicKey);
    }
}