生成 {@link SecretKey}，仅用于对称加密和摘要算法密钥生成

@param algorithm 算法
@param key 密钥，如果为{@code null} 自动生成随机密钥
@return {@link SecretKey}
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;
	}
839892
public static String encrypt(String secretKey, String plainText) {
        if (plainText == null) {
            return null;
        } else if (plainText.startsWith("$CRYPT::")) {
             // Avoid encrypting already encrypted text - APIMAN-1201
             return plainText;
        }
        
        byte[] encrypted;
        Cipher cipher;
        try {
            SecretKeySpec skeySpec = keySpecFromSecretKey(secretKey);
            
            cipher = Cipher.getInstance("AES"); //$NON-NLS-1$
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        try {
            encrypted = cipher.doFinal(plainText.getBytes());
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
        return "$CRYPT::" + new String(Base64.encodeBase64(encrypted)); //$NON-NLS-1$
    }
252128
public static void setEncryptionKey(final String key) {

		if (key == null) {

			logger.info("set_encryption_key() was called with null parameter, resetting global secret key");

			// reset hash
			secretKeyHash = null;
			return;
		}

		try {

			secretKeyHash = MessageDigest.getInstance(HASH_ALGO).digest(key.getBytes("UTF-8"));

		} catch (Throwable t) {
			logger.error("Unable to set secret key: {}", t.getMessage());
		}
	}
892256
public SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        final SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        keyGen.init(256, random);
        return this.secretKey = keyGen.generateKey();
    }
752579
private static String createSignature(String     stringToSign,
                                          String     awsSecretKey,
                                          String     algorithm)
            throws SignatureException {

        assert stringToSign != null;
        assert awsSecretKey != null;
        assert algorithm != null;

        String signature;

        try {
            byte[] secretyKeyBytes = awsSecretKey.getBytes(UTF8_CHARSET);
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretyKeyBytes,
                                                            algorithm);
            Mac mac = Mac.getInstance(algorithm);
            mac.init(secretKeySpec);

            byte[] data = stringToSign.getBytes(UTF8_CHARSET);

            byte[] rawHmac = mac.doFinal(data);
            signature = rfc3986Conformance(new String(Codec.base64Encode(rawHmac)));
        } catch (Exception e) {
            throw new SignatureException("Failed to generate HMAC : " +
                                                               e.getMessage());
        }

        return signature;
    }
244221
public static KeyPair generateKeyPair(String algorithm, int bits)
        throws GeneralSecurityException {
        KeyPairGenerator generator = null;
        if (provider == null) {
            generator = KeyPairGenerator.getInstance(algorithm);
        } else {
            generator = KeyPairGenerator.getInstance(algorithm, provider);
        }
        generator.initialize(bits);
        return generator.generateKeyPair();
    }
509139
public static SecretKey deserializeSecretKey(byte[] keyData, String algorithm) {
        LOGGER.trace("deserialize secret key from data using algorithm \"{}\"", algorithm);
        return new SecretKeySpec(keyData, algorithm);
    }
1078466
public static void createPairKey() {
		try {
			// 根据特定的算法一个密钥对生成器
			KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
			// 加密随机数生成器 (RNG)
			SecureRandom random = new SecureRandom();
			// 重新设置此随机对象的种子
			random.setSeed(1000);
			// 使用给定的随机源（和默认的参数集合）初始化确定密钥大小的密钥对生成器
			keygen.initialize(512, random);// keygen.initialize(512);
			// 生成密钥组
			KeyPair keys = keygen.generateKeyPair();
			// 得到公匙
			PublicKey pubkey = keys.getPublic();
			// 得到私匙
			PrivateKey prikey = keys.getPrivate();
			// 将公匙私匙写入到文件当中
			doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
1148443
private void storeKey(SecretKey key) {
        final String keyStoreFile = getMain().getFileSystemManager().getSystemLocation() + File.separator + "izou.keystore";
        KeyStore keyStore = createKeyStore(keyStoreFile, "4b[X:+H4CS&avY<)");

        try {
            KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(key);
            KeyStore.PasswordProtection keyPassword = new KeyStore.PasswordProtection("Ev45j>eP}QTR?K9_".toCharArray());
            keyStore.setEntry("izou_key", keyStoreEntry, keyPassword);
            keyStore.store(new FileOutputStream(keyStoreFile), "4b[X:+H4CS&avY<)".toCharArray());
        } catch (NoSuchAlgorithmException | KeyStoreException
                | CertificateException | IOException e) {
            logger.error("Unable to store key", e);
        }
    }
649504
@Override
	public final Key keyFromPassword(char[] password) {
		try {
			SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
			int keyLength = Math.min(Cipher.getMaxAllowedKeyLength(algorithm), maximumKeyLength);
			KeySpec spec = new PBEKeySpec(password, salt, iterationCount, keyLength);
			SecretKey tmp = factory.generateSecret(spec);
			return new SecretKeySpec(tmp.getEncoded(), algorithm);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		} catch (InvalidKeySpecException e) {
			throw new RuntimeException(e);
		}
	}
865608
protected static final void setRSAKey(byte[][] key) {
        BigInteger[] k = new BigInteger[8];
        for (int i = 0; i < 8; i++) {
            if (key[i] != null) {
                k[i] = new BigInteger(1, key[i]);
            }
        }

        if (k[3].compareTo(k[4]) < 0) {
            BigInteger tmp;
            tmp = k[3];
            k[3] = k[4];
            k[4] = tmp;
            tmp = k[5];
            k[5] = k[6];
            k[6] = tmp;
            k[7] = null;
        }
        if (k[7] == null) {
            k[7] = k[4].modInverse(k[3]);
        }
        if (k[0] == null) {
            k[0] = k[3].multiply(k[4]);
        }
        if (k[1] == null) {
            k[1] = k[2].modInverse(k[3].subtract(BigInteger.valueOf(1)).multiply(k[4].subtract(BigInteger.valueOf(1))));
        }
        if (k[5] == null) {
            k[5] = k[1].remainder(k[3].subtract(BigInteger.valueOf(1)));
        }
        if (k[6] == null) {
            k[6] = k[1].remainder(k[4].subtract(BigInteger.valueOf(1)));
        }
        for (int i = 0; i < 8; i++) {
            key[i] = k[i].toByteArray();
        }

    }
91880
public static Key generateKey(final Random random) {
        final byte[] signingKey = new byte[signingKeyBytes];
        random.nextBytes(signingKey);
        final byte[] encryptionKey = new byte[encryptionKeyBytes];
        random.nextBytes(encryptionKey);
        return new Key(signingKey, encryptionKey);
    }
141529
public byte[] wrapKeyByKey(Key key,Key wrapKey)
	{
		try {
    		if(key==null ||wrapKey==null)
    		{
    			return null;
    		}
			Cipher cipher=Cipher.getInstance(algorithm);
			//使用私钥包裹模式
			cipher.init(Cipher.WRAP_MODE,wrapKey);
			return cipher.wrap(key);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
    	return null;
	}
941636
public static SshKeyPair generateKeyPair(String algorithm, int bits)
			throws IOException, SshException {

		if (!SSH2_RSA.equalsIgnoreCase(algorithm)
				&& !SSH2_DSA.equalsIgnoreCase(algorithm)) {
			throw new IOException(algorithm
					+ " is not a supported key algorithm!");
		}

		SshKeyPair pair = new SshKeyPair();

		if (SSH2_RSA.equalsIgnoreCase(algorithm)) {
			pair = ComponentManager.getInstance().generateRsaKeyPair(bits);
		} else {
			pair = ComponentManager.getInstance().generateDsaKeyPair(bits);
		}

		return pair;
	}
891033
public SecretKey generateKey() {
        SecretKey key = null;
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(128);
            key = generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            logger.error("Unable to generate AES key", e);
        }

        return key;
    }
552197
public static String encryptToDES(SecretKey key, String info) {
		// 定义 加密算法,可用 DES,DESede,Blowfish
		String Algorithm = "DES";
		// 加密随机数生成器 (RNG),(可以不写)
		SecureRandom sr = new SecureRandom();
		// 定义要生成的密文
		byte[] cipherByte = null;
		try {
			// 得到加密/解密器
			Cipher c1 = Cipher.getInstance(Algorithm);
			// 用指定的密钥和模式初始化Cipher对象
			// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
			c1.init(Cipher.ENCRYPT_MODE, key, sr);
			// 对要加密的内容进行编码处理,
			cipherByte = c1.doFinal(info.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 返回密文的十六进制形式
		return byte2hex(cipherByte);
	}
729703
public Key< byte[]> start( final String algorithm) throws NoSuchAlgorithmException {
		final MessageDigest digest = MessageDigest.getInstance( algorithm);
		final Key< byte[]> object = new Key< byte[]>();
		consumers.put( object, new Consumer< byte[]>() {
			public void consume( final ByteBuffer buffer) {
				try {
					digest.update( buffer);
				} catch ( Exception e) {
					throw new RuntimeException( e);
				}
			}
			public byte[] finish() {
				try {
					return digest.digest();
				} catch ( Exception e) {
					throw new RuntimeException( e);
				}
			}
		});
		return object;
	}