Java Code Examples for java.security.spec.InvalidKeySpecException

The following are top voted examples for showing how to use java.security.spec.InvalidKeySpecException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 7 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
Example 2
Project: openjdk-jdk10   File: PBKDF2Translate.java   View source code 6 votes vote down vote up
/**
 * The test case scenario implemented in the method: - create my own secret
 * Key2 as an instance of a class implements PBEKey - spoil the key (set
 * iteration count to 0, for example) - try to translate key -
 * InvalidKeyException is expected.
 *
 * @return true if InvalidKeyException occurred; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public boolean translateSpoiledKey() throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    // derive the key
    SecretKey key1 = getMyOwnSecretKey();

    // spoil the key
    ((MyPBKDF2SecretKey) key1).spoil();

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    try {
        SecretKey key2 = skf.translateKey(key1);
    } catch (InvalidKeyException ike) {
        // this is expected
        return true;
    }

    return false;
}
 
Example 3
Project: firebase-admin-java   File: FirebaseTokenVerifierTest.java   View source code 6 votes vote down vote up
private void initCrypto(String privateKey, String certificate)
    throws NoSuchAlgorithmException, InvalidKeySpecException {
  byte[] privateBytes = BaseEncoding.base64().decode(privateKey);
  KeySpec spec = new PKCS8EncodedKeySpec(privateBytes);
  String serviceAccountCertificates =
      String.format("{\"%s\" : \"%s\"}", PRIVATE_KEY_ID, certificate);

  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder()
          .setLowLevelHttpResponse(
              new MockLowLevelHttpResponse().setContent(serviceAccountCertificates))
          .build();
  this.privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
  this.verifier =
      new FirebaseTokenVerifier.Builder()
          .setClock(CLOCK)
          .setPublicKeysManager(
              new GooglePublicKeysManager.Builder(mockTransport, FACTORY)
                  .setClock(CLOCK)
                  .setPublicCertsEncodedUrl(FirebaseTokenVerifier.CLIENT_CERT_URL)
                  .build())
          .setProjectId(PROJECT_ID)
          .build();
}
 
Example 4
Project: CS4160-trustchain-android   File: Key.java   View source code 6 votes vote down vote up
/**
 * Load a private key from a base64 encoded string
 * @param key The base64 encoded key
 * @return The private key
 */
public static PrivateKey loadPrivateKey(String key) {
    KeyFactory kf = getKeyFactory();
    if(kf == null) {
        return null;
    }

    byte[] rawKey = Base64.decode(key, Base64.DEFAULT);
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(rawKey);
    try {
        return kf.generatePrivate(ks);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Project: BaseClient   File: CryptManager.java   View source code 6 votes vote down vote up
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
 
Example 6
Project: BedrockProxy   File: BedrockProxy.java   View source code 6 votes vote down vote up
@Override
public void onEnable() {
    instance = this;

    try {
        mojangPublicKey = KeyFactory.getInstance("EC").generatePublic(
                new X509EncodedKeySpec(Base64
                        .getDecoder()
                        .decode("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V")
                )
        );
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }

    networkManager = new NetworkManager();
}
 
Example 7
Project: incubator-servicecomb-java-chassis   File: RSAUtils.java   View source code 6 votes vote down vote up
/**
 * 
 * if has performance problem ,change Signature to ThreadLocal instance  
 * @param publicKey public key after base64 encode 
 * @param sign 签名
 * @param content original content 
 * @return verify result
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public static boolean verify(String publicKey, String sign, String content)
    throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
  if (null == kf) {
    throw new NoSuchAlgorithmException(RSA_ALG + " KeyFactory not available");
  }
  byte[] bytes = decoder.decode(publicKey);
  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  PublicKey pubKey = kf.generatePublic(keySpec);
  Signature signature = Signature.getInstance(SIGN_ALG);
  signature.initVerify(pubKey);
  signature.update(content.getBytes());
  return signature.verify(decoder.decode(sign));
}
 
Example 8
Project: incubator-servicecomb-java-chassis   File: TestRSAAuthenticationToken.java   View source code 6 votes vote down vote up
@Test
public void testRSAAuthenticationToken()
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
  String tokenstr =
      "[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwg[email protected]WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=";
  RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr);
  String contents = token.plainToken();
  Assert.assertEquals(
      "[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ",
      contents);
  String sign = token.getSign();
  Assert.assertEquals(
      "WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=",
      sign);
  String pubKey =
      "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB";
  Assert.assertTrue(RSAUtils.verify(pubKey, sign, contents));
}
 
Example 9
Project: VerifySignedJar   File: VerfiyPKCS7Info.java   View source code 6 votes vote down vote up
/**
 * 从hex string生成公钥
 * 
 * @param stringN
 * @param stringE
 * @return 构造好的公钥
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey createPublicKey(String stringN, String stringE)
		throws NoSuchAlgorithmException, InvalidKeySpecException {
	try {
		BigInteger N = new BigInteger(stringN, 16); // hex base
		BigInteger E = new BigInteger(stringE, 16); // hex base

		RSAPublicKeySpec spec = new RSAPublicKeySpec(N, E);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		return kf.generatePublic(spec);
	} catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
 
Example 10
Project: CrashCoin   File: Cryptography.java   View source code 6 votes vote down vote up
/**
 * Convert encoded private and public keys (bytes) to Private / PublicKey
 * interfaces and generate a KeyPair from them in order to construct a
 * Wallet object in the signIn method<br>
 * <b>Two different encoding</b>
 *
 * @param publicKeyBytes the public key with encoding X509
 * @param privateKeyBytes the private key with encoding PKCS8
 * @return the key pair
 */
public static KeyPair createKeyPairFromEncodedKeys(byte[] publicKeyBytes, byte[] privateKeyBytes) {
    // Generate specs
    final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
    final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    
    try {
        // Create PublicKey and PrivateKey interfaces using the factory
        final PrivateKey privateKey = dsaKeyFactory.generatePrivate(privateKeySpec);
        final PublicKey publicKey = dsaKeyFactory.generatePublic(publicKeySpec);
        
        return new KeyPair(publicKey, privateKey);
    } catch (InvalidKeySpecException ex) {
        logAndAbort("Unable to create key pair. Abort!", ex);
    }
    return null;
}
 
Example 11
Project: pay   File: AlipaySignature.java   View source code 6 votes vote down vote up
public static String rsaSign(String content, String privateKey,
                             String charset) throws AlipayApiException {
    try {
        PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(privateKey.getBytes()));

        java.security.Signature signature = java.security.Signature
            .getInstance(AlipayConstants.SIGN_ALGORITHMS);

        signature.initSign(priKey);

        if (StringUtils.isEmpty(charset)) {
            signature.update(content.getBytes());
        } else {
            signature.update(content.getBytes(charset));
        }

        byte[] signed = signature.sign();

        return new String(Base64.encodeBase64(signed));
    } catch (InvalidKeySpecException ie) {
        throw new AlipayApiException("RSA私钥格式不正确,请检查是否正确配置了PKCS8格式的私钥", ie);
    } catch (Exception e) {
        throw new AlipayApiException("RSAcontent = " + content + "; charset = " + charset, e);
    }
}
 
Example 12
Project: DecompiledMinecraft   File: CryptManager.java   View source code 6 votes vote down vote up
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
 
Example 13
Project: CryptoKnight   File: FileEncrypt.java   View source code 6 votes vote down vote up
public static String CBCEncrypt(int alg, int KeySize, String inFile, String pwd, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, DataLengthException, IllegalStateException, InvalidCipherTextException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
{
	String res = "";
	
	byte[] plain = loadFile(inFile);
	
	Encryptor enc = new Encryptor();
	enc.setParameters(KeySize, alg);
	enc.setEncParameters(alg, pwd, KeySize, mode);
	byte[] bytesRes = enc.CBCEncrypt(plain, alg);
	
	save2File(inFile + ".enc", bytesRes);
	
	res = "Done! file contents encrypted and saved to a corresponding enc file!"; 
	return res;
}
 
Example 14
Project: jdk8u-jdk   File: DESKeyFactory.java   View source code 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 DESKeySpec) {
            return new DESKey(((DESKeySpec)keySpec).getKey());
        }

        if (keySpec instanceof SecretKeySpec) {
            return new DESKey(((SecretKeySpec)keySpec).getEncoded());
        }

        throw new InvalidKeySpecException(
                "Inappropriate key specification");

    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
 
Example 15
Project: atbash-octopus   File: LocalSecret.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
    // TODO This code is demo as the passphrase is hardcoded.
    SystemInfo info = new SystemInfo();
    String salt = info.getHardware().getProcessor().getProcessorID() + info.getOperatingSystem().getFileSystem().getFileStores()[0].getUUID();

    String passPhrase = "Rudy";

    // PBKDF2WithHmacSHA1 available on Java 7 and Java 8. Must match value used on LocalSecretFactory.
    // TODO possible usage scenario. using theis local secret, the end user can create the OfflineToken with a Web application (where he needs to authenticate himself
    // in order to create a correct OfflineToken instance for the user.
    byte[] secret = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(
            new PBEKeySpec(passPhrase.toCharArray(), salt.getBytes(), 1024, 256)).getEncoded();

    String secret64 = Base64Codec.encodeToString(secret, true);
    System.out.println("Local secret value is " + secret64);

}
 
Example 16
Project: appinventor-extensions   File: PasswordHash.java   View source code 6 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(char[] password, String correctHash)
    throws NoSuchAlgorithmException, InvalidKeySpecException
{
    // Decode the hash into its parameters
    String[] params = correctHash.split(":");
    int iterations = Integer.parseInt(params[ITERATION_INDEX]);
    byte[] salt = fromHex(params[SALT_INDEX]);
    byte[] hash = fromHex(params[PBKDF2_INDEX]);
    // Compute the hash of the provided password, using the same salt,
    // iteration count, and hash length
    byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
    // Compare the hashes in constant time. The password is correct if
    // both hashes match.
    return slowEquals(hash, testHash);
}
 
Example 17
Project: coddy   File: SecurityUtils.java   View source code 6 votes vote down vote up
/**
 * This method will hash the password and salt combination. Be careful, this method will erase the password after hashed it.
 * You must be sure that you do not need it after using this method.
 *
 * @param password the password who needs to be hashed
 * @param salt     some list of <code>byte</code> which will be included in the password
 * @return a hash of the password and salting combination.
 */
public static byte[] hash(char[] password, byte[] salt) {
    final PBEKeySpec spec = new PBEKeySpec(password, salt, SecurityUtils.ITERATIONS, SecurityUtils.KEY_LENGTH);

    try {
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SecurityUtils.ALGORITHM);
        SecretKey key = secretKeyFactory.generateSecret(spec);
        return key.getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        LOGGER.debug(e.getMessage(), e);
        throw new SecurityException(e);
    } finally {
        // erase the password in the char array in order to not retrieve it in the java memory
        spec.clearPassword();
    }
}
 
Example 18
Project: convertigo-engine   File: Crypto2.java   View source code 6 votes vote down vote up
private Crypto2(String passPhrase) throws InvalidKeySpecException, NoSuchAlgorithmException,
		NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
	/* Ciphering options:
		Mode = CipherMode.CBC,-( Cipher-block chaining)
		Padding = PaddingMode.PKCS7 or PKCS5,
		KeySize = 128,
		BlockSize = 128,
		Key = keyBytes - password,
		IV = keyBytes  - password
	*/
	
	// Create the key
	byte[] bytesOfMessage = passPhrase.getBytes("UTF-8");
	MessageDigest md = MessageDigest.getInstance("MD5");
	byte[] bytesPassphrase = md.digest(bytesOfMessage);
	SecretKeySpec key = new SecretKeySpec(bytesPassphrase, "AES");
	
    // Parameter specific algorithm
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(bytesPassphrase); 

	ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
	dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
}
 
Example 19
Project: ipack   File: KeyFactory.java   View source code 6 votes vote down vote up
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            PrivateKeyInfo info = PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded());
            PrivateKey     key = BouncyCastleProvider.getPrivateKey(info);

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

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

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
 
Example 20
Project: ipack   File: KeyFactory.java   View source code 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 21
Project: dremio-oss   File: SimpleUserService.java   View source code 6 votes vote down vote up
@Override
public void authenticate(String userName, String password) throws UserLoginException {
  final UserInfo userInfo = findUserByUserName(userName);
  if (userInfo == null) {
    throw new UserLoginException(userName, "Invalid user credentials");
  }
  try {
    UserAuth userAuth = userInfo.getAuth();
    final byte[] authKey = buildUserAuthKey(password, userAuth.getPrefix().toByteArray());
    if (!slowEquals(authKey, userAuth.getAuthKey().toByteArray())) {
      throw new UserLoginException(userName, "Invalid user credentials");
    }
  } catch (InvalidKeySpecException ikse) {
    throw new UserLoginException(userName, "Invalid user credentials");
  }
}
 
Example 22
Project: RISE-V2G   File: SecurityUtils.java   View source code 6 votes vote down vote up
/**
 * Returns the ECPublicKey instance from its encoded raw bytes. 
 * The first byte has the fixed value 0x04 indicating the uncompressed form.
 * Therefore, the byte array must be of form: [0x04, x coord of point (32 bytes), y coord of point (32 bytes)]
 * 
 * @param publicKeyBytes The byte array representing the encoded raw bytes of the public key
 * @return The ECPublicKey instance
 */
public static ECPublicKey getPublicKey(byte[] publicKeyBytes) {
	// First we separate x and y of coordinates into separate variables
    byte[] x = new byte[32];
    byte[] y = new byte[32];
    System.arraycopy(publicKeyBytes, 1, x, 0, 32);
    System.arraycopy(publicKeyBytes, 33, y, 0, 32);
    
    try {
		KeyFactory kf = KeyFactory.getInstance("EC");
		
		AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
		parameters.init(new ECGenParameterSpec("secp256r1"));
		ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
		
		ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec);
		ECPublicKey ecPublicKey = (ECPublicKey) kf.generatePublic(ecPublicKeySpec);
		return ecPublicKey;
    } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get public key from raw bytes", e);
        return null;
	}
}
 
Example 23
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 6 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
Example 24
Project: OpenJSharp   File: DESKeyFactory.java   View source code 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 DESKeySpec) {
            return new DESKey(((DESKeySpec)keySpec).getKey());
        }

        if (keySpec instanceof SecretKeySpec) {
            return new DESKey(((SecretKeySpec)keySpec).getEncoded());
        }

        throw new InvalidKeySpecException(
                "Inappropriate key specification");

    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
 
Example 25
Project: openjdk-jdk10   File: PBKDF2Translate.java   View source code 6 votes vote down vote up
/**
 * The test case scenario implemented in the method: - derive PBKDF2 key
 * using the given algorithm; - translate the key - check if the translated
 * and original keys have the same key value.
 *
 * @return true if the test case passed; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 */
public boolean generateAndTranslateKey() throws NoSuchAlgorithmException,
        InvalidKeySpecException, InvalidKeyException {
    // derive PBKDF2 key
    SecretKey key1 = getSecretKeyForPBKDF2(algoToTest);

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    SecretKey key2 = skf.translateKey(key1);

    // check if it still the same after translation
    if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
        System.err.println("generateAndTranslateKey test case failed: the "
                + "key1 and key2 values in its primary encoding format are "
                + "not the same for " + algoToTest + "algorithm.");
        return false;
    }

    return true;
}
 
Example 26
Project: osc-core   File: KeyStoreProvider.java   View source code 6 votes vote down vote up
/**
 * Puts password in keystore under given alias. Secret password is secured with the entry password.
 * The keystore change is persistant.
 * @param alias alias to secret password
 * @param password password to store as secret
 * @param entryPassword password to secret password
 * @throws KeyStoreProviderException
 */
public void putPassword(String alias, String password, String entryPassword) throws KeyStoreProviderException {
    try {
        LOG.info(String.format("Putting password with alias %s in keystore ...", alias));

        SecretKeyFactory skFactory = SecretKeyFactory.getInstance(SECRET_KEY_PASSWORD_ALGORITHM);
        SecretKey secret = skFactory.generateSecret(new PBEKeySpec(password.toCharArray()));
        this.keystore.setEntry(alias, new KeyStore.SecretKeyEntry(secret),
                new KeyStore.PasswordProtection(entryPassword.toCharArray()));
        factory.persist(this.keystore);
    } catch (NoSuchAlgorithmException nsae) {
        throw new KeyStoreProviderException("Algorithm used to create PBE secret cannot be found.", nsae);
    } catch (InvalidKeySpecException ikse) {
        throw new KeyStoreProviderException("Invalid key spec used to create PBE secret.", ikse);
    } catch (KeyStoreException kse) {
        throw new KeyStoreProviderException("Failed to put PBE secret to keystore.", kse);
    } catch (Exception e) {
        throw new KeyStoreProviderException("Failed to put PBE secret in keystore", e);
    }
}
 
Example 27
Project: openjdk-jdk10   File: PBKDF2TranslateTest.java   View source code 5 votes vote down vote up
/**
 * The test case scenario implemented in the method: - derive Key1 for the
 * given PBKDF2 algorithm - create my own secret Key2 as an instance of a
 * class implements PBEKey - translate Key2 - check if the key value of the
 * translated key and Key1 are the same.
 */
private void testMyOwnSecretKey(byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException,
        InvalidKeyException {
    SecretKey key1 = getSecretKeyForPBKDF2(algoForTest, salt);
    SecretKey key2 = getMyOwnSecretKey(salt);

    // Is it actually the same?
    if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
        throw new RuntimeException(
                "We shouldn't be here. The key1 and key2 values in its"
                        + " primary encoding format have to be the same!");
    }

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest);
    SecretKey key3 = skf.translateKey(key2);

    // Check if it still the same after translation
    if (!Arrays.equals(key1.getEncoded(), key3.getEncoded())) {
        System.out.println("Key1=" + new String(key1.getEncoded())
                + " key3=" + new String(key3.getEncoded()) + " salt="
                + new String(salt));
        throw new RuntimeException(
                "testMyOwnSecretKey test case failed: the key1  and key3"
                        + " values in its primary encoding format are not"
                        + " the same for " + algoForTest + " algorithm.");
    }

}
 
Example 28
Project: GitHub   File: PubkeyUtils.java   View source code 5 votes vote down vote up
public static KeyPair recoverKeyPair(byte[] encoded) throws NoSuchAlgorithmException,
		InvalidKeySpecException {
	final String algo = getAlgorithmForOid(getOidFromPkcs8Encoded(encoded));

	final KeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);

	final KeyFactory kf = KeyFactory.getInstance(algo);
	final PrivateKey priv = kf.generatePrivate(privKeySpec);

	return new KeyPair(recoverPublicKey(kf, priv), priv);
}
 
Example 29
Project: incubator-servicecomb-java-chassis   File: TestRSAUtil.java   View source code 5 votes vote down vote up
@Test
public void testSignVerify2()
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
  String sign =
      "WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=";
  String content =
      "[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ";
  String pubKey =
      "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB";
  Assert.assertTrue(RSAUtils.verify(pubKey, sign, content));

}
 
Example 30
Project: incubator-servicecomb-java-chassis   File: RSAProviderTokenManager.java   View source code 5 votes vote down vote up
public boolean valid(String token) {
  try {
    RSAAuthenticationToken rsaToken = RSAAuthenticationToken.fromStr(token);
    if (null == rsaToken) {
      LOGGER.error("token format is error, perhaps you need to set auth handler at consumer");
      return false;
    }
    if (tokenExprired(rsaToken)) {
      LOGGER.error("token is expired");
      return false;
    }
    if (validatedToken.contains(rsaToken)) {
      LOGGER.info("found vaildate token in vaildate pool");
      return true;
    }

    String sign = rsaToken.getSign();
    String content = rsaToken.plainToken();
    String publicKey = getPublicKey(rsaToken.getInstanceId(), rsaToken.getServiceId());
    boolean verify = RSAUtils.verify(publicKey, sign, content);
    if (verify && !tokenExprired(rsaToken)) {
      validatedToken.add(rsaToken);
      return true;
    }

    LOGGER.error("token verify error");
    return false;

  } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | SignatureException e) {
    LOGGER.error("verfiy error", e);
    return false;
  }
}
 
Example 31
Project: HerbertyyRepository   File: RSAUtils.java   View source code 5 votes vote down vote up
/**
 * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
 *
 * @param keyBytes
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
        InvalidKeySpecException
{
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}
 
Example 32
Project: InComb   File: PasswordUtil.java   View source code 5 votes vote down vote up
/**
 * Returns a salted and hashed password using the provided hash.<br>
 * Note - side effect: the password is destroyed (the char[] is filled with
 * zeros)
 *
 * @param password
 *            the password to be hashed
 * @param salt
 *            a 16 bytes salt, ideally obtained with the getNextSalt method
 *
 * @return the hashed password with a pinch of salt
 */
public static byte[] hash(final char[] password, final byte[] salt) {
	final PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
	Arrays.fill(password, Character.MIN_VALUE);
	try {
		final SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
		return skf.generateSecret(spec).getEncoded();
	} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
		throw new HashingException("Error while hashing a password: " + e.getMessage(), e);
	} finally {
		spec.clearPassword();
	}
}
 
Example 33
Project: LJFramework   File: RSAUtils.java   View source code 5 votes vote down vote up
/**
 * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
 *
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(RSA, "BC");
        return keyFactory.generatePublic(keySpec);
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 34
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 5 votes vote down vote up
private static PrivateKey createPrivateKeyFromPemFile(final String keyFileName) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException 
{
	// Loads a privte key from the specified key file name
    final PemReader pemReader = new PemReader(new FileReader(keyFileName));
    final PemObject pemObject = pemReader.readPemObject();
    final byte[] pemContent = pemObject.getContent();
    pemReader.close();
    final PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(pemContent);
    final KeyFactory keyFactory = getKeyFactoryInstance();
    final PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec);
    return privateKey;
}
 
Example 35
Project: CryptoKnight   File: TextEncrypt.java   View source code 5 votes vote down vote up
public static String CBCEncrypt(String plain, String pwd, int KeySize, int alg, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, DataLengthException, IllegalStateException, InvalidCipherTextException 
{
	
	String res = "";
	
	Encryptor enc = new Encryptor();
	enc.setParameters(KeySize, alg);
	enc.setEncParameters(alg, pwd, KeySize, mode);
	byte[] bytesRes = enc.CBCEncrypt(plain.getBytes("UTF-8"), alg);
	
	res = new String(Base64.encodeBase64(bytesRes));
	
	return res;
}
 
Example 36
Project: openjdk-jdk10   File: DOMKeyValue.java   View source code 5 votes vote down vote up
private static PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) {
    try {
        return kf.generatePublic(keyspec);
    } catch (InvalidKeySpecException e) {
        //@@@ should dump exception to log
        return null;
    }
}
 
Example 37
Project: openjdk-jdk10   File: KeyFactory.java   View source code 5 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.
 */
public final PrivateKey generatePrivate(KeySpec keySpec)
        throws InvalidKeySpecException {
    if (serviceIterator == null) {
        return spi.engineGeneratePrivate(keySpec);
    }
    Exception failure = null;
    KeyFactorySpi mySpi = spi;
    do {
        try {
            return mySpi.engineGeneratePrivate(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 generate private key", failure);
}
 
Example 38
Project: jdk8u-jdk   File: PBMacDoFinalVsUpdate.java   View source code 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 39
Project: bitcoin-paper-wallet   File: AesUtility.java   View source code 5 votes vote down vote up
AesUtility(String passPhrase, byte [] salt, int iterationCount, int keyStrength) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException {
	SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
	KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength);
	SecretKey secret = factory.generateSecret(spec);
	key = new SecretKeySpec(secret.getEncoded(), "AES");
	dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
}
 
Example 40
Project: FirefoxData-android   File: DSACryptoImplementation.java   View source code 5 votes vote down vote up
public static BrowserIDKeyPair fromJSONObject(ExtendedJSONObject o) throws InvalidKeySpecException, NoSuchAlgorithmException {
  try {
    ExtendedJSONObject privateKey = o.getObject(BrowserIDKeyPair.JSON_KEY_PRIVATEKEY);
    ExtendedJSONObject publicKey = o.getObject(BrowserIDKeyPair.JSON_KEY_PUBLICKEY);
    if (privateKey == null) {
      throw new InvalidKeySpecException("privateKey must not be null");
    }
    if (publicKey == null) {
      throw new InvalidKeySpecException("publicKey must not be null");
    }
    return new BrowserIDKeyPair(createPrivateKey(privateKey), createPublicKey(publicKey));
  } catch (NonObjectJSONException e) {
    throw new InvalidKeySpecException("privateKey and publicKey must be JSON objects");
  }
}