Java 类java.security.spec.InvalidKeySpecException 实例源码

项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
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;
}
项目:openjdk-jdk10    文件:PBKDF2Translate.java   
/**
 * 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;
}
项目:firebase-admin-java    文件:FirebaseTokenVerifierTest.java   
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();
}
项目:CS4160-trustchain-android    文件:Key.java   
/**
 * 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;
}
项目:BaseClient    文件:CryptManager.java   
/**
 * 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;
}
项目:BedrockProxy    文件:BedrockProxy.java   
@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();
}
项目:incubator-servicecomb-java-chassis    文件:RSAUtils.java   
/**
 * 
 * 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));
}
项目:VerifySignedJar    文件:VerfiyPKCS7Info.java   
/**
 * 从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;
}
项目:CrashCoin    文件:Cryptography.java   
/**
 * 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;
}
项目:pay    文件:AlipaySignature.java   
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);
    }
}
项目:DecompiledMinecraft    文件:CryptManager.java   
/**
 * 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;
}
项目:CryptoKnight    文件:FileEncrypt.java   
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;
}
项目:jdk8u-jdk    文件:DESKeyFactory.java   
/**
 * 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());
    }
}
项目:atbash-octopus    文件:LocalSecret.java   
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);

}
项目:appinventor-extensions    文件:PasswordHash.java   
/**
 * 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);
}
项目:coddy    文件:SecurityUtils.java   
/**
 * 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();
    }
}
项目:convertigo-engine    文件:Crypto2.java   
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);
}
项目:ipack    文件:KeyFactory.java   
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());
}
项目:ipack    文件:KeyFactory.java   
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());
}
项目:dremio-oss    文件:SimpleUserService.java   
@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");
  }
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * 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;
    }
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
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;
}
项目:OpenJSharp    文件:DESKeyFactory.java   
/**
 * 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());
    }
}
项目:openjdk-jdk10    文件:PBKDF2Translate.java   
/**
 * 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;
}
项目:osc-core    文件:KeyStoreProvider.java   
/**
 * 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);
    }
}
项目:openjdk-jdk10    文件:PBKDF2TranslateTest.java   
/**
 * 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.");
    }

}
项目:GitHub    文件:PubkeyUtils.java   
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);
}
项目:incubator-servicecomb-java-chassis    文件:RSAProviderTokenManager.java   
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;
  }
}
项目:HerbertyyRepository    文件:RSAUtils.java   
/**
 * 通过公钥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;
}
项目:InComb    文件:PasswordUtil.java   
/**
 * 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();
    }
}
项目:LJFramework    文件:RSAUtils.java   
/**
 * 通过公钥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;
    }
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
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;
}
项目:CryptoKnight    文件:TextEncrypt.java   
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;
}
项目:openjdk-jdk10    文件:DOMKeyValue.java   
private static PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) {
    try {
        return kf.generatePublic(keyspec);
    } catch (InvalidKeySpecException e) {
        //@@@ should dump exception to log
        return null;
    }
}
项目:openjdk-jdk10    文件:KeyFactory.java   
/**
 * 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);
}
项目:jdk8u-jdk    文件:PBMacDoFinalVsUpdate.java   
/**
 * 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);
}
项目:bitcoin-paper-wallet    文件:AesUtility.java   
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");
}
项目:FirefoxData-android    文件:DSACryptoImplementation.java   
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");
  }
}