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

项目: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();
}
项目:NoteBuddy    文件:AesCbcWithIntegrity.java   
/**
 * A function that generates password-based AES & HMAC keys. It prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @param password The password to derive the keys from.
 * @return The AES & HMAC keys.
 * @throws GeneralSecurityException if AES is not implemented on this system,
 *                                  or a suitable RNG is not available
 */
public static SecretKeys generateKeyFromPassword(String password, byte[] salt) throws GeneralSecurityException {
    fixPrng();
    //Get enough random bytes for both the AES key and the HMAC key:
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
            PBE_ITERATION_COUNT, AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS);
    SecretKeyFactory keyFactory = SecretKeyFactory
            .getInstance(PBE_ALGORITHM);
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();

    // Split the random bytes into two parts:
    byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS /8);
    byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS /8, AES_KEY_LENGTH_BITS /8 + HMAC_KEY_LENGTH_BITS /8);

    //Generate the AES key
    SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER);

    //Generate the HMAC key
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
项目:ipack    文件:RainbowKeyFactorySpi.java   
/**
 * Converts, if possible, a key specification into a
 * {@link BCRainbowPublicKey}. Currently, the following key specifications are
 * supported:{@link X509EncodedKeySpec}.
 * <p/>
 * <p/>
 * <p/>
 * The ASN.1 definition of a public key's structure is
 * <p/>
 * <pre>
 *    RainbowPublicKey ::= SEQUENCE {
 *      oid            OBJECT IDENTIFIER        -- OID identifying the algorithm
 *      docLength      Integer                  -- length of signable msg
 *      coeffquadratic SEQUENCE OF OCTET STRING -- quadratic (mixed) coefficients
 *      coeffsingular  SEQUENCE OF OCTET STRING -- singular coefficients
 *      coeffscalar       OCTET STRING             -- scalar coefficients
 *       }
 * </pre>
 * <p/>
 * <p/>
 *
 * @param keySpec the key specification
 * @return the Rainbow public key
 * @throws InvalidKeySpecException if the KeySpec is not supported.
 */
public PublicKey engineGeneratePublic(KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof RainbowPublicKeySpec)
    {
        return new BCRainbowPublicKey((RainbowPublicKeySpec)keySpec);
    }
    else if (keySpec instanceof X509EncodedKeySpec)
    {
        // get the DER-encoded Key according to X.509 from the spec
        byte[] encKey = ((X509EncodedKeySpec)keySpec).getEncoded();

        // decode the SubjectPublicKeyInfo data structure to the pki object
        try
        {
            return generatePublic(SubjectPublicKeyInfo.getInstance(encKey));
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }

    throw new InvalidKeySpecException("Unknown key specification: " + keySpec + ".");
}
项目:openjdk-jdk10    文件:GenerationTests.java   
private static PrivateKey getECPrivateKey(String curve) throws Exception {
    String s;
    ECParameterSpec params;
    switch (curve) {
        case "P256":
            s = EC_P256_S;
            params = EC_P256_PARAMS;
            break;
        case "P384":
            s = EC_P384_S;
            params = EC_P384_PARAMS;
            break;
        case "P521":
            s = EC_P521_S;
            params = EC_P521_PARAMS;
            break;
        default:
            throw new Exception("Unsupported curve: " + curve);
    }
    KeyFactory kf = KeyFactory.getInstance("EC");
    KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
    return kf.generatePrivate(kspec);
}
项目:openjdk-jdk10    文件:Des3DkCrypto.java   
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
    throws GeneralSecurityException {
    // NoSuchAlgorithException
    SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");

    // InvalidKeyException
    KeySpec spec = new DESedeKeySpec(key, 0);

    // InvalidKeySpecException
    SecretKey secretKey = factory.generateSecret(spec);

    // IV
    if (ivec == null) {
        ivec = ZERO_IV;
    }

    // NoSuchAlgorithmException, NoSuchPaddingException
    // NoSuchProviderException
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);

    // InvalidKeyException, InvalidAlgorithParameterException
    cipher.init(mode, secretKey, encIv);

    return cipher;
}
项目: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());
    }
}
项目: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());
}
项目:dpg-android    文件:dpg.java   
/**
 * A method to get 64 random bytes deterministically based on user input
 * And to also fill the queue with numbers
 **/
private void fill_q(char[] sentence, char[] word, String encryption) throws NoSuchAlgorithmException, InvalidKeySpecException {
    // 512 bit key_length (64 bytes). Python and C++ use bytes rather than bits.
    KeySpec ks = new PBEKeySpec(sentence, chars_to_bytes(word), iterations, key_length_in_bytes * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(encryption);

    if (debug) {
        String hex_random_bytes = byte_array_to_hex(skf.generateSecret(ks).getEncoded());
        System.out.println("PBKDF2:  " + hex_random_bytes);
    }

    byte[] random_bytes = skf.generateSecret(ks).getEncoded();

    for (byte b : random_bytes) {
        if (debug) {
            // & 0xFF ensures the int is unsigned
            System.out.println(((int) b) & 0xFF);
        }

        number_queue.add(((int) b) & 0xFF);
    }
}
项目:ipack    文件:BaseKeyFactorySpi.java   
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof X509EncodedKeySpec)
    {
        try
        {
            return generatePublic(SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException("encoded key spec not recognised");
        }
    }
    else
    {
        throw new InvalidKeySpecException("key spec not recognised");
    }
}
项目:ipack    文件:BaseKeyFactorySpi.java   
protected KeySpec engineGetKeySpec(
    Key key,
    Class spec)
    throws InvalidKeySpecException
{
    if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8"))
    {
        return new PKCS8EncodedKeySpec(key.getEncoded());
    }
    else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509"))
    {
        return new X509EncodedKeySpec(key.getEncoded());
    }

    throw new InvalidKeySpecException("not implemented yet " + key + " " + spec);
}
项目:unity-obb-downloader    文件:AESObfuscator.java   
/**
 * @param salt an array of random bytes to use for each (un)obfuscation
 * @param applicationId application identifier, e.g. the package name
 * @param deviceId device identifier. Use as many sources as possible to
 *    create this unique identifier.
 */
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
        KeySpec keySpec =
            new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
        SecretKey tmp = factory.generateSecret(keySpec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
        mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
    } catch (GeneralSecurityException e) {
        // This can't happen on a compatible Android device.
        throw new RuntimeException("Invalid environment", e);
    }
}
项目:text_converter    文件:AESObfuscator.java   
/**
 * @param salt an array of random bytes to use for each (un)obfuscation
 * @param applicationId application identifier, e.g. the package name
 * @param deviceId device identifier. Use as many sources as possible to
 *    create this unique identifier.
 */
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
        KeySpec keySpec =   
            new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
        SecretKey tmp = factory.generateSecret(keySpec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
        mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
    } catch (GeneralSecurityException e) {
        // This can't happen on a compatible Android device.
        throw new RuntimeException("Invalid environment", e);
    }
}
项目:AngularAndSpring    文件:PasswordEncryption.java   
public String getEncryptedPassword(String password, String salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // PBKDF2 with SHA-1 as the hashing algorithm. Note that the NIST
    // specifically names SHA-1 as an acceptable hashing algorithm for PBKDF2
    String algorithm = "PBKDF2WithHmacSHA1";
    // SHA-1 generates 160 bit hashes, so that's what makes sense here
    int derivedKeyLength = 160;
    // Pick an iteration count that works for you. The NIST recommends at
    // least 1,000 iterations:
    // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
    // iOS 4.x reportedly uses 10,000:
    // http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-passwords/
    int iterations = 20000;
    char[] pwd = new String(password).toCharArray();        
    KeySpec spec = new PBEKeySpec(pwd, Base64.getDecoder().decode(salt), iterations, derivedKeyLength);
    SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
    byte[] bytes = f.generateSecret(spec).getEncoded();
    return Base64.getEncoder().encodeToString(bytes);
}
项目:openjdk-jdk10    文件:PBKDF2HmacSHA1Factory.java   
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpecCl 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");
    }
}
项目:lams    文件:RSA_SHA1.java   
private PublicKey getPublicKeyFromPem(String pem) 
throws GeneralSecurityException, IOException {

    InputStream stream = new ByteArrayInputStream(
            pem.getBytes("UTF-8"));

    PEMReader reader = new PEMReader(stream);
    byte[] bytes = reader.getDerBytes();    
    PublicKey pubKey;

    if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
        KeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory fac = KeyFactory.getInstance("RSA");
        pubKey = fac.generatePublic(keySpec);
    } else if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
        pubKey = getPublicKeyFromDerCert(bytes);
    } else {
        throw new IOException("Invalid PEM fileL: Unknown marker for " + 
                " public key or cert " + reader.getBeginMarker());
    }

    return pubKey;
}
项目:FirefoxData-android    文件:DSACryptoImplementation.java   
public static SigningPrivateKey createPrivateKey(BigInteger x, BigInteger p, BigInteger q, BigInteger g) throws NoSuchAlgorithmException, InvalidKeySpecException {
  if (x == null) {
    throw new IllegalArgumentException("x must not be null");
  }
  if (p == null) {
    throw new IllegalArgumentException("p must not be null");
  }
  if (q == null) {
    throw new IllegalArgumentException("q must not be null");
  }
  if (g == null) {
    throw new IllegalArgumentException("g must not be null");
  }
  KeySpec keySpec = new DSAPrivateKeySpec(x, p, q, g);
  KeyFactory keyFactory = KeyFactory.getInstance("DSA");
  DSAPrivateKey privateKey = (DSAPrivateKey) keyFactory.generatePrivate(keySpec);
  return new DSASigningPrivateKey(privateKey);
}
项目:FirefoxData-android    文件:DSACryptoImplementation.java   
public static VerifyingPublicKey createPublicKey(BigInteger y, BigInteger p, BigInteger q, BigInteger g) throws NoSuchAlgorithmException, InvalidKeySpecException {
  if (y == null) {
    throw new IllegalArgumentException("n must not be null");
  }
  if (p == null) {
    throw new IllegalArgumentException("p must not be null");
  }
  if (q == null) {
    throw new IllegalArgumentException("q must not be null");
  }
  if (g == null) {
    throw new IllegalArgumentException("g must not be null");
  }
  KeySpec keySpec = new DSAPublicKeySpec(y, p, q, g);
  KeyFactory keyFactory = KeyFactory.getInstance("DSA");
  DSAPublicKey publicKey = (DSAPublicKey) keyFactory.generatePublic(keySpec);
  return new DSAVerifyingPublicKey(publicKey);
}
项目:OpenJSharp    文件:DHKeyFactory.java   
/**
 * Generates a public key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the public key
 *
 * @return the public key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected PublicKey engineGeneratePublic(KeySpec keySpec)
    throws InvalidKeySpecException
{
    try {
        if (keySpec instanceof DHPublicKeySpec) {
            DHPublicKeySpec dhPubKeySpec = (DHPublicKeySpec)keySpec;
            return new DHPublicKey(dhPubKeySpec.getY(),
                                   dhPubKeySpec.getP(),
                                   dhPubKeySpec.getG());

        } else if (keySpec instanceof X509EncodedKeySpec) {
            return new DHPublicKey
                (((X509EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification", e);
    }
}
项目:jdk8u-jdk    文件:PBKDF2HmacSHA1Factory.java   
/**
 * 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");
    }
}
项目:SlotNSlot_Android    文件:AESObfuscator.java   
/**
 * @param salt an array of random bytes to use for each (un)obfuscation
 * @param applicationId application identifier, e.g. the package name
 * @param deviceId device identifier. Use as many sources as possible to
 *    create this unique identifier.
 */
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
        KeySpec keySpec =   
            new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
        SecretKey tmp = factory.generateSecret(keySpec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
        mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
    } catch (GeneralSecurityException e) {
        // This can't happen on a compatible Android device.
        throw new RuntimeException("Invalid environment", e);
    }
}
项目:OpenJSharp    文件:PBKDF2HmacSHA1Factory.java   
/**
 * 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");
    }
}
项目:OpenJSharp    文件:DSAKeyFactory.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.
 */
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());
    }
}
项目: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());
    }
}
项目:OpenJSharp    文件:DESedeKeyFactory.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 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());
    }
}
项目:OpenJSharp    文件:DESedeKeyFactory.java   
/**
 * 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<?> keySpec)
    throws InvalidKeySpecException {

    try {
        if ((key instanceof SecretKey)
            && (key.getAlgorithm().equalsIgnoreCase("DESede"))
            && (key.getFormat().equalsIgnoreCase("RAW"))) {

            // Check if requested key spec is amongst the valid ones
            if (DESedeKeySpec.class.isAssignableFrom(keySpec)) {
                return new DESedeKeySpec(key.getEncoded());

            } else {
                throw new InvalidKeySpecException
                    ("Inappropriate key specification");
            }

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key format/algorithm");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException("Secret key has wrong size");
    }
}
项目: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);
}
项目:jdk8u-jdk    文件:KeyUtil.java   
/**
 * Returns whether the key spec is valid or not.
 * <P>
 * Note that this method is only apply to DHPublicKeySpec at present.
 *
 * @param  keySpec
 *         the key spec object, cannot be null
 *
 * @throws NullPointerException if {@code keySpec} is null
 * @throws InvalidKeyException if {@code keySpec} is invalid
 */
public static final void validate(KeySpec keySpec)
        throws InvalidKeyException {
    if (keySpec == null) {
        throw new NullPointerException(
            "The key spec to be validated cannot be null");
    }

    if (keySpec instanceof DHPublicKeySpec) {
        validateDHPublicKey((DHPublicKeySpec)keySpec);
    }
}
项目:AndroRW    文件:Aes.java   
private static byte[] getRawKey(String password) throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), "AndroRW".getBytes(), 65536, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    return secret.getEncoded();
}
项目:ipack    文件:DES.java   
protected KeySpec engineGetKeySpec(
    SecretKey key,
    Class keySpec)
throws InvalidKeySpecException
{
    if (keySpec == null)
    {
        throw new InvalidKeySpecException("keySpec parameter is null");
    }
    if (key == null)
    {
        throw new InvalidKeySpecException("key parameter is null");
    }

    if (SecretKeySpec.class.isAssignableFrom(keySpec))
    {
        return new SecretKeySpec(key.getEncoded(), algName);
    }
    else if (DESKeySpec.class.isAssignableFrom(keySpec))
    {
        byte[]  bytes = key.getEncoded();

        try
        {
            return new DESKeySpec(bytes);
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }

    throw new InvalidKeySpecException("Invalid KeySpec");
}
项目:ipack    文件:DES.java   
protected SecretKey engineGenerateSecret(
    KeySpec keySpec)
throws InvalidKeySpecException
{
    if (keySpec instanceof DESKeySpec)
    {
        DESKeySpec desKeySpec = (DESKeySpec)keySpec;
        return new SecretKeySpec(desKeySpec.getKey(), "DES");
    }

    return super.engineGenerateSecret(keySpec);
}
项目:ipack    文件:DESede.java   
protected SecretKey engineGenerateSecret(
    KeySpec keySpec)
throws InvalidKeySpecException
{
    if (keySpec instanceof DESedeKeySpec)
    {
        DESedeKeySpec desKeySpec = (DESedeKeySpec)keySpec;
        return new SecretKeySpec(desKeySpec.getKey(), "DESede");
    }

    return super.engineGenerateSecret(keySpec);
}
项目:ipack    文件:BaseSecretKeyFactory.java   
protected KeySpec engineGetKeySpec(
    SecretKey key,
    Class keySpec)
throws InvalidKeySpecException
{
    if (keySpec == null)
    {
        throw new InvalidKeySpecException("keySpec parameter is null");
    }
    if (key == null)
    {
        throw new InvalidKeySpecException("key parameter is null");
    }

    if (SecretKeySpec.class.isAssignableFrom(keySpec))
    {
        return new SecretKeySpec(key.getEncoded(), algName);
    }

    try
    {
        Class[] parameters = { byte[].class };

        Constructor c = keySpec.getConstructor(parameters);
        Object[]    p = new Object[1];

        p[0] = key.getEncoded();

        return (KeySpec)c.newInstance(p);
    }
    catch (Exception e)
    {
        throw new InvalidKeySpecException(e.toString());
    }
}
项目:ipack    文件:KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof ECPrivateKeySpec)
    {
        return new BCDSTU4145PrivateKey((ECPrivateKeySpec)keySpec);
    }
    else if (keySpec instanceof java.security.spec.ECPrivateKeySpec)
    {
        return new BCDSTU4145PrivateKey((java.security.spec.ECPrivateKeySpec)keySpec);
    }

    return super.engineGeneratePrivate(keySpec);
}
项目:ipack    文件:KeyFactorySpi.java   
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof ECPublicKeySpec)
    {
        return new BCDSTU4145PublicKey((ECPublicKeySpec)keySpec);
    }
    else if (keySpec instanceof java.security.spec.ECPublicKeySpec)
    {
        return new BCDSTU4145PublicKey((java.security.spec.ECPublicKeySpec)keySpec);
    }

    return super.engineGeneratePublic(keySpec);
}
项目:ipack    文件:KeyFactory.java   
protected KeySpec engineGetKeySpec(Key key, Class keySpec)
    throws InvalidKeySpecException
{
    if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8"))
    {
        return new PKCS8EncodedKeySpec(key.getEncoded());
    }
    else if (keySpec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509"))
    {
        return new X509EncodedKeySpec(key.getEncoded());
    }

    throw new InvalidKeySpecException("not implemented yet " + key + " " + keySpec);
}
项目:ipack    文件:KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
        KeySpec    keySpec)
throws InvalidKeySpecException
{
    if (keySpec instanceof GOST3410PrivateKeySpec)
    {
        return new BCGOST3410PrivateKey((GOST3410PrivateKeySpec)keySpec);
    }

    return super.engineGeneratePrivate(keySpec);
}
项目:jdk8u-jdk    文件:KeyFactory.java   
/**
 * 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);
}
项目:ipack    文件:KeyFactorySpi.java   
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof DSAPublicKeySpec)
    {
        return new BCDSAPublicKey((DSAPublicKeySpec)keySpec);
    }

    return super.engineGeneratePublic(keySpec);
}
项目:ipack    文件:KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof DHPrivateKeySpec)
    {
        return new BCDHPrivateKey((DHPrivateKeySpec)keySpec);
    }

    return super.engineGeneratePrivate(keySpec);
}
项目:ipack    文件:KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            //
            // in case it's just a RSAPrivateKey object... -- openSSL produces these
            //
            try
            {
                return new BCRSAPrivateCrtKey(
                    RSAPrivateKey.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
            }
            catch (Exception ex)
            {
                throw new ExtendedInvalidKeySpecException("unable to process key spec: " + e.toString(), e);
            }
        }
    }
    else if (keySpec instanceof RSAPrivateCrtKeySpec)
    {
        return new BCRSAPrivateCrtKey((RSAPrivateCrtKeySpec)keySpec);
    }
    else if (keySpec instanceof RSAPrivateKeySpec)
    {
        return new BCRSAPrivateKey((RSAPrivateKeySpec)keySpec);
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}