使用指定keySpec构建对称加密的key

@param algorithm 算法名称，当前仅支持AES和DES
@param keySpec   keySpec，多次调用该方法生成的key等效
@return 对称加密的key
481269
public static SecretKey buildKey(AbstractCipher.Algorithms algorithm, byte[] keySpec) {
        SecretKeySpec key = new SecretKeySpec(keySpec, algorithm.name());
        return key;
    }
329548
public static SecretKey generateKey(String algorithm, byte[] key) {
		Assert.notBlank(algorithm, "Algorithm is blank!");
		SecretKey secretKey = null;
		if (algorithm.startsWith("PBE")) {
			// PBE密钥
			secretKey = generatePBEKey(algorithm, (null == key) ? null : StrUtil.str(key, CharsetUtil.CHARSET_UTF_8).toCharArray());
		} else if (algorithm.startsWith("DES")) {
			// DES密钥
			secretKey = generateDESKey(algorithm, key);
		} else {
			// 其它算法密钥
			secretKey = (null == key) ? generateKey(algorithm) : new SecretKeySpec(key, algorithm);
		}
		return secretKey;
	}
148622
public HMac init(String algorithm, SecretKey key){
		try {
			mac = Mac.getInstance(algorithm);
			if(null != key){
				this.secretKey = key;
			}else{
				this.secretKey = SecureUtil.generateKey(algorithm);
			}
			mac.init(this.secretKey);
		} catch (Exception e) {
			throw new CryptoException(e);
		}
		return this;
	}
525796
public SymmetricCrypto init(String algorithm, SecretKey key) {
		this.secretKey = key;
		if (algorithm.startsWith("PBE")) {
			// 对于PBE算法使用随机数加盐
			this.params = new PBEParameterSpec(RandomUtil.randomBytes(8), 100);
		}
		this.cipher = SecureUtil.createCipher(algorithm);
		return this;
	}
1287252
private Cipher createCipher() throws GeneralSecurityException {
		if(algorithmProvider != null) {
			return Cipher.getInstance(algorithm, algorithmProvider);
		} else {
			return Cipher.getInstance(algorithm);
		}
	}
568314
public static SecretKey generateKey(String algorithm, int keySize) {
		algorithm = getMainAlgorithm(algorithm);
		
		final KeyGenerator keyGenerator = getKeyGenerator(algorithm);
		if (keySize > 0) {
			keyGenerator.init(keySize);
		} else if (SymmetricAlgorithm.AES.getValue().equals(algorithm)) {
			// 对于AES的密钥，除非指定，否则强制使用128位
			keyGenerator.init(128);
		}
		return keyGenerator.generateKey();
	}
726146
public static SignatureUtil buildInstance(String privateKey, String publicKey,
                                              Algorithms algorithms) {
        return new SignatureUtilImpl(privateKey, publicKey, algorithms);
    }
82627
public static KeyPair generateKeyPair(String algorithm, AlgorithmParameterSpec params) {
		return generateKeyPair(algorithm, null, params);
	}
202487
public static PublicKey generatePublicKey(String algorithm, KeySpec keySpec) {
		return KeyUtil.generatePublicKey(algorithm, keySpec);
	}
246434
public static PrivateKey generatePrivateKey(String algorithm, KeySpec keySpec) {
		if (null == keySpec) {
			return null;
		}
		algorithm = getAlgorithmAfterWith(algorithm);
		try {
			return getKeyFactory(algorithm).generatePrivate(keySpec);
		} catch (Exception e) {
			throw new CryptoException(e);
		}
	}
1341285
public static String getFingerprint(byte[] encoded, String algorithm)
			throws SshException {

		Digest md5 = (Digest) ComponentManager.getInstance().supportedDigests()
				.getInstance(algorithm);

		md5.putBytes(encoded);

		byte[] digest = md5.doFinal();

		StringBuffer buf = new StringBuffer();
		int ch;
		for (int i = 0; i < digest.length; i++) {
			ch = digest[i] & 0xFF;
			if (i > 0) {
				buf.append(':');
			}
			buf.append(HEX[(ch >>> 4) & 0x0F]);
			buf.append(HEX[ch & 0x0F]);
		}

		return buf.toString();
	}
1335914
public static CipherUtil buildInstance(Algorithms algorithms, byte[] keySpec) {
        SecretKey key = KeyTools.buildKey(algorithms, keySpec);
        return new SymmetryCipher(algorithms, key);
    }
31062
public static byte[] decipher(byte[] encrypted_bytes, String crypto_algorithm)
                    throws InvalidPasswordCipherException, UnsupportedCryptoAlgorithmException {

        if (crypto_algorithm == null) {
            logger.logp(Level.SEVERE, PasswordCipherUtil.class.getName(), "decipher", "PASSWORDUTIL_UNKNOWN_ALGORITHM",
                        new Object[] { "null", formatSupportedCryptoAlgorithms() });
            throw new UnsupportedCryptoAlgorithmException();
        }

        byte[] decrypted_bytes = null;

        if (AES.equalsIgnoreCase(crypto_algorithm)) {
            decrypted_bytes = aesDecipher(encrypted_bytes, decrypted_bytes);
        } else if (XOR.equalsIgnoreCase(crypto_algorithm)) {
            decrypted_bytes = xor(encrypted_bytes);
        } else if (HASH.equalsIgnoreCase(crypto_algorithm)) {
            throw new InvalidPasswordCipherException(MessageUtils.getMessage("PASSWORDUTIL_ERROR_UNSUPPORTED_OPERATION", crypto_algorithm));
        } else if (CUSTOM.equalsIgnoreCase(crypto_algorithm) || crypto_algorithm.startsWith(CUSTOM_COLON)) {

            CustomPasswordEncryption cpe = getCustomImpl();
            if (cpe != null) {
                int index = crypto_algorithm.indexOf(':');
                String keyAlias = null;

                if (index != -1) {
                    keyAlias = crypto_algorithm.substring(index + 1);
                }

                try {
                    decrypted_bytes = cpe.decrypt(new EncryptedInfo(encrypted_bytes, keyAlias));
                    if (logger.isLoggable(Level.FINE))
                        logger.fine("Successfully decrypted password using custom encryption plug point.");
                } catch (Exception e) {
                    logger.logp(Level.SEVERE, PasswordCipherUtil.class.getName(), "decipher", "PASSWORDUTIL_CUSTOM_DECRYPTION_ERROR", e);
                    throw (InvalidPasswordCipherException) new InvalidPasswordCipherException(e.getMessage()).initCause(e);
                }
            } else {
                logger.logp(Level.SEVERE, PasswordCipherUtil.class.getName(), "decipher", "PASSWORDUTIL_CUSTOM_SERVICE_DOES_NOT_EXIST");
                throw new UnsupportedCryptoAlgorithmException();
            }
        } else {
            logger.logp(Level.SEVERE, PasswordCipherUtil.class.getName(), "decipher", "PASSWORDUTIL_UNKNOWN_ALGORITHM", new Object[] { crypto_algorithm,
                                                                                                                                      formatSupportedCryptoAlgorithms() });
            throw new UnsupportedCryptoAlgorithmException();
        }

        if (decrypted_bytes == null) {
            throw new InvalidPasswordCipherException("The output is null.");
        }
        return decrypted_bytes;
    }
288457
private static SignatureHolder buildSignatureHolder(String privateKey, String publicKey,
                                                        Algorithms algorithms) {
        log.debug("构建SignatureHolder");
        try {
            log.debug("构建公钥以及验签器");
            RSAPublicKey pubKey = (RSAPublicKey) KeyTools.getPublicKeyFromX509("RSA",
                new ByteArrayInputStream(publicKey.getBytes()));
            Signature verify = Signature.getInstance(algorithms.toString());
            verify.initVerify(pubKey);

            log.debug("构建私钥以及签名器");
            RSAPrivateKey priKey = (RSAPrivateKey) KeyTools.getPrivateKeyFromPKCS8("RSA",
                new ByteArrayInputStream(privateKey.getBytes()));
            Signature sign = Signature.getInstance(algorithms.toString());
            sign.initSign(priKey);

            log.debug("SignatureHolder构建成功");
            return new SignatureHolder(sign, verify, priKey, pubKey);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new SecureException("创建验签器[" + algorithms + "]失败", e);
        }
    }
29016
public static Cipher createCipher(String algorithm) {
		final Provider provider = GlobalBouncyCastleProvider.INSTANCE.getProvider();

		Cipher cipher;
		try {
			cipher = (null == provider) ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider);
		} catch (Exception e) {
			throw new CryptoException(e);
		}

		return cipher;
	}
909966
public static KeyPair generateKeyPair(String algorithm, AlgorithmParameterSpec params) {
		return KeyUtil.generateKeyPair(algorithm, params);
	}
616988
public static function castKey(XMLSecurityKey $key, $algorithm, $type = 'public')
    {
        assert('is_string($algorithm)');
        assert('$type === "public" || $type === "private"');
        // do nothing if algorithm is already the type of the key
        if ($key->type === $algorithm) {
            return $key;
        }

        if (!OneLogin_Saml2_Utils::isSupportedSigningAlgorithm($algorithm)) {
            throw new \Exception('Unsupported signing algorithm.');
        }

        $keyInfo = openssl_pkey_get_details($key->key);
        if ($keyInfo === false) {
            throw new Exception('Unable to get key details from XMLSecurityKey.');
        }
        if (!isset($keyInfo['key'])) {
            throw new Exception('Missing key in public key details.');
        }
        $newKey = new XMLSecurityKey($algorithm, array('type'=>$type));
        $newKey->loadKey($keyInfo['key']);
        return $newKey;
    }