本文整理了Java中javax.crypto.Cipher.init()
方法的一些代码示例,展示了Cipher.init()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cipher.init()
方法的具体详情如下:
包路径:javax.crypto.Cipher
类名称:Cipher
方法名:init
[英]Initializes this cipher instance with the specified key.
The cipher is initialized for the specified operational mode (one of: encryption, decryption, key wrapping or key unwrapping) depending on opmode.
If this cipher instance needs any algorithm parameters or random values that the specified key can not provide, the underlying implementation of this cipher is supposed to generate the required parameters (using its provider or random values).
When a cipher instance is initialized by a call to any of the init methods, the state of the instance is overridden, meaning that it is equivalent to creating a new instance and calling its initmethod.
[中]使用指定的密钥初始化此密码实例。
根据opmode,针对指定的操作模式(加密、解密、密钥包装或密钥展开)初始化密码。
如果此密码实例需要指定密钥无法提供的任何算法参数或随机值,则此密码的底层实现应生成所需的参数(使用其提供程序或随机值)。
当通过调用任何init方法初始化密码实例时,该实例的状态将被覆盖,这意味着它相当于创建一个新实例并调用其initmethod。
代码示例来源:origin: jenkinsci/jenkins
private static Cipher toCipher(RSAKey key, int mode) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(mode, (Key)key);
return cipher;
}
代码示例来源:origin: stackoverflow.com
/* Decrypt the message, given derived key and initialization vector. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8");
System.out.println(plaintext);
代码示例来源:origin: pentaho/pentaho-kettle
public static Cipher initDecryptionCipher( Key unwrappedKey, byte[] unencryptedKey ) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
Cipher decryptionCip = Cipher.getInstance( SINGLE_KEY_ALGORITHM );
if ( unwrappedKey != null ) {
decryptionCip.init( Cipher.ENCRYPT_MODE, unwrappedKey );
} else {
SecretKeySpec sks = new SecretKeySpec( unencryptedKey, SINGLE_KEY_ALGORITHM );
decryptionCip.init( Cipher.ENCRYPT_MODE, sks );
}
return decryptionCip;
}
代码示例来源:origin: rapidoid/rapidoid
private byte[] aes(byte[] data, byte[] key, byte[] iv, int mode) throws Exception {
Cipher cipher = Cipher.getInstance(AES_MODE);
cipher.init(mode, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
return cipher.doFinal(data);
}
代码示例来源:origin: aa112901/remusic
/**
* 私钥解密
*
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//模长
int key_len = privateKey.getModulus().bitLength() / 8;
byte[] bytes = data.getBytes();
byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
System.err.println(bcd.length);
//如果密文长度大于模长则要分组解密
String ming = "";
byte[][] arrays = splitArray(bcd, key_len);
for (byte[] arr : arrays) {
ming += new String(cipher.doFinal(arr));
}
return ming;
}
代码示例来源:origin: stackoverflow.com
skf = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = skf.generateSecret(ks);
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
String decryptedText=null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
} catch (Exception e) {
String decrypted=td.decrypt(encrypted);
System.out.println("String To Encrypt: "+ target);
System.out.println("Encrypted String:" + encrypted);
System.out.println("Decrypted String:" + decrypted);
代码示例来源:origin: Graylog2/graylog2-server
private static PKCS8EncodedKeySpec createKeySpec(byte[] keyBytes, String password)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException {
if (Strings.isNullOrEmpty(password)) {
return new PKCS8EncodedKeySpec(keyBytes);
}
final EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(keyBytes);
final SecretKeyFactory kf = SecretKeyFactory.getInstance(pkInfo.getAlgName());
final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
final SecretKey secretKey = kf.generateSecret(keySpec);
@SuppressWarnings("InsecureCryptoUsage") final Cipher cipher = Cipher.getInstance(pkInfo.getAlgName());
cipher.init(Cipher.DECRYPT_MODE, secretKey, pkInfo.getAlgParameters());
return pkInfo.getKeySpec(cipher);
}
代码示例来源:origin: gocd/gocd
public static String encryptUsingAES(SecretKey secretKey, String dataToEncrypt) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteCipherText = aesCipher.doFinal(dataToEncrypt.getBytes());
return Base64.getEncoder().encodeToString(byteCipherText);
}
代码示例来源:origin: bwssytems/ha-bridge
private String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(habridgeKey));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}
代码示例来源:origin: jenkinsci/jenkins
public CombinedCipherOutputStream(OutputStream out, Cipher asym, String algorithm) throws IOException, GeneralSecurityException {
super(out);
// create a new symmetric cipher key used for this stream
String keyAlgorithm = getKeyAlgorithm(algorithm);
SecretKey symKey = KeyGenerator.getInstance(keyAlgorithm).generateKey();
// place the symmetric key by encrypting it with asymmetric cipher
out.write(asym.doFinal(symKey.getEncoded()));
// the rest of the data will be encrypted by this symmetric cipher
Cipher sym = Secret.getCipher(algorithm);
sym.init(Cipher.ENCRYPT_MODE,symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded()));
super.out = new CipherOutputStream(out,sym);
}
代码示例来源:origin: kaaproject/kaa
private void decodeSessionKey(byte[] encodedKey) throws
InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException {
Cipher sessionKeyCipher = RSA_CIPHER.get();
sessionKeyCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] sessionKeyBytes = sessionKeyCipher.doFinal(encodedKey);
sessionKey = new SecretKeySpec(sessionKeyBytes, 0, SESSION_KEY_SIZE / 8, SESSION_KEY_ALGORITHM);
}
代码示例来源:origin: org.apache.hadoop/hadoop-common
@Override
public void init(byte[] key, byte[] iv) throws IOException {
Preconditions.checkNotNull(key);
Preconditions.checkNotNull(iv);
contextReset = false;
try {
cipher.init(mode, new SecretKeySpec(key, "AES"),
new IvParameterSpec(iv));
} catch (Exception e) {
throw new IOException(e);
}
}
代码示例来源:origin: jenkinsci/jenkins
/**
* Upgrades a connection with transport encryption by the specified symmetric cipher.
*
* @return
* A new {@link Connection} object that includes the transport encryption.
*/
public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException {
Cipher cout = Cipher.getInstance(algorithm);
cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherOutputStream o = new CipherOutputStream(out, cout);
Cipher cin = Cipher.getInstance(algorithm);
cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherInputStream i = new CipherInputStream(in, cin);
return new Connection(i,o);
}
代码示例来源:origin: jenkinsci/jenkins
public static String protect(String secret) {
try {
Cipher cipher = Secret.getCipher(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, DES_KEY);
return new String(Base64.encode(cipher.doFinal((secret+ MAGIC).getBytes("UTF-8"))));
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
}
代码示例来源:origin: stackoverflow.com
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
byte[] ciphertext = pbeCipher.doFinal(encodedprivkey);
代码示例来源:origin: jenkinsci/jenkins
/**
* Returns a {@link Cipher} object for encrypting with this key using the provided initialization vector.
* @param iv the initialization vector
* @return the cipher
*/
@Restricted(NoExternalUse.class) // TODO pending API
public Cipher encrypt(byte[] iv) {
try {
Cipher cipher = Secret.getCipher(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, getKey(), new IvParameterSpec(iv));
return cipher;
} catch (GeneralSecurityException e) {
throw new AssertionError(e);
}
}
代码示例来源:origin: Graylog2/graylog2-server
@Nullable
public static String encrypt(String plainText, String encryptionKey, String salt) {
try {
@SuppressWarnings("CIPHER_INTEGRITY")
Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(salt.getBytes("UTF-8")));
return Hex.encodeToString(cipher.doFinal(plainText.getBytes("UTF-8")));
} catch (Exception e) {
LOG.error("Could not encrypt value.", e);
}
return null;
}
代码示例来源:origin: stackoverflow.com
byte[] expBytes = Base64.decodeBase64(exponentElem.getText().trim()));
byte[] modBytes = Base64.decodeBase64(modulusElem.getText().trim());
byte[] dBytes = Base64.decodeBase64(dElem.getText().trim());
BigInteger modules = new BigInteger(1, modBytes);
BigInteger exponent = new BigInteger(1, expBytes);
BigInteger d = new BigInteger(1, dBytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA");
String input = "test";
RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modules, exponent);
PublicKey pubKey = factory.generatePublic(pubSpec);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
System.out.println("encrypted: " + new String(encrypted));
RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modules, d);
PrivateKey privKey = factory.generatePrivate(privSpec);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println("decrypted: " + new String(decrypted));
代码示例来源:origin: apache/nifi
/**
* Initializes a {@link Cipher} object with the given PBE parameters.
*
* @param algorithm the algorithm
* @param provider the JCA provider
* @param password the password
* @param salt the salt
* @param iterationCount the KDF iteration count
* @param encryptMode true to encrypt; false to decrypt
* @return the initialized Cipher
* @throws IllegalArgumentException if any parameter is invalid
*/
public static Cipher initPBECipher(String algorithm, String provider, String password, byte[] salt, int iterationCount, boolean encryptMode) throws IllegalArgumentException {
try {
// Initialize secret key from password
final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
SecretKey tempKey = factory.generateSecret(pbeKeySpec);
final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
Cipher cipher = Cipher.getInstance(algorithm, provider);
cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
return cipher;
} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new IllegalArgumentException("One or more parameters to initialize the PBE cipher were invalid", e);
}
}
代码示例来源:origin: gocd/gocd
public static String decryptUsingAES(SecretKey secretKey, String dataToDecrypt) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytePlainText = aesCipher.doFinal(Base64.getDecoder().decode(dataToDecrypt));
return new String(bytePlainText);
}
}
内容来源于网络,如有侵权,请联系作者删除!