javax.crypto.Cipher类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(12.3k)|赞(0)|评价(0)|浏览(532)

本文整理了Java中javax.crypto.Cipher类的一些代码示例,展示了Cipher类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cipher类的具体详情如下:
包路径:javax.crypto.Cipher
类名称:Cipher

Cipher介绍

[英]This class provides access to implementations of cryptographic ciphers for encryption and decryption. Cipher classes can not be instantiated directly, one has to call the Cipher's getInstance method with the name of a requested transformation, optionally with a provider. A transformation specifies an operation (or a set of operations) as a string in the form:

  • "algorithm/mode/padding" or
  • "algorithm"
    algorithm is the name of a cryptographic algorithm, mode is the name of a feedback mode and padding is the name of a padding scheme. If mode and/or padding values are omitted, provider specific default values will be used.

A valid transformation would be:

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
When a block cipher is requested in in stream cipher mode, the number of bits to be processed at a time can be optionally specified by appending it to the mode name. e.g. "AES/CFB8/NoPadding". If no number is specified, a provider specific default value is used.
[中]此类提供对加密密码实现的访问,以进行加密和解密。密码类不能直接实例化,必须使用请求转换的名称调用密码的getInstance方法,可以选择使用提供程序。转换将一个操作(或一组操作)指定为以下形式的字符串:
*“算法/模式/填充”或
*“算法”
algorithm是加密算法的名称,mode是反馈模式的名称,padding是填充方案的名称。如果省略模式和/或填充值,则将使用特定于提供程序的默认值。
有效的转换是:
密码c=密码。getInstance(“AES/CBC/PKCS5P”);
当在流密码模式下请求分组密码时,可以通过将其附加到模式名称来选择性地指定一次要处理的位数。e、 g.“AES/CFB8/NOP添加”。如果未指定数字,则使用特定于提供程序的默认值。

代码示例

代码示例来源: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: kingthy/TVRemoteIME

/**
 * Signs the ADB SHA1 payload with the private key of this object.
 * @param payload SHA1 payload to sign
 * @return Signed SHA1 payload
 * @throws GeneralSecurityException If signing fails
 */
public byte[] signAdbTokenPayload(byte[] payload) throws GeneralSecurityException
{    
  Cipher c = Cipher.getInstance("RSA/ECB/NoPadding");
  
  c.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
  
  c.update(SIGNATURE_PADDING);
  
  return c.doFinal(payload);
}

代码示例来源: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: stackoverflow.com

/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));

代码示例来源: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: stackoverflow.com

byte[] iv = new byte[cipher.getBlockSize()];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(keyString.getBytes());
byte[] key = new byte[16];
System.arraycopy(digest.digest(), 0, key, 0, key.length);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
System.out.println("encrypted: " + new String(encrypted));
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println("decrypted: " + new String(decrypted, "UTF-8"));

代码示例来源:origin: plutext/docx4j

protected static Cipher initCipherForBlock(Cipher cipher, int block,
  EncryptionInfoBuilder builder, SecretKey skey, int encryptMode)
throws GeneralSecurityException {
  EncryptionVerifier ver = builder.getVerifier();
  HashAlgorithm hashAlgo = ver.getHashAlgorithm();
  byte blockKey[] = new byte[4];
  LittleEndian.putUInt(blockKey, 0, block);
  MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
  hashAlg.update(skey.getEncoded());
  byte encKey[] = hashAlg.digest(blockKey);
  EncryptionHeader header = builder.getHeader();
  int keyBits = header.getKeySize();
  encKey = CryptoFunctions.getBlock0(encKey, keyBits / 8);
  if (keyBits == 40) {
    encKey = CryptoFunctions.getBlock0(encKey, 16);
  }
  SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm());
  if (cipher == null) {
    cipher = CryptoFunctions.getCipher(key, header.getCipherAlgorithm(), null, null, encryptMode);
  } else {
    cipher.init(encryptMode, key);
  }
  return cipher;
}

代码示例来源:origin: rhuss/jolokia

private Cipher createCipher(byte[] salt, final int mode)
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
  digest.reset();
    digest.update(pwdAsBytes);
    digest.update(salt, 0, 8);
    result = digest.digest();
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  cipher.init(mode, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));

代码示例来源:origin: oblac/jodd

public PBKDF2Encryptor(final String passPhrase, final byte[] salt, final int iterationCount, final int i1) {
  this.iterationCount = iterationCount;
  try {
    // create the key
    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, i1);
    SecretKey tmp = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(keySpec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    // encryptor
    ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    ecipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = ecipher.getParameters();
    byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    // decryptor
    dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
  }
  catch (Exception ex) {
    throw new IllegalArgumentException(ex);
  }
}

代码示例来源:origin: shuzheng/zheng

SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(ENCODE_RULES.getBytes());
keygen.init(128, random);
byte[] raw = originalKey.getEncoded();
SecretKey key = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] byteDecode = cipher.doFinal(byteContent);
String aesDecode = new String(byteDecode, "utf-8");
return aesDecode;

代码示例来源:origin: wildfly/wildfly

hmacKey = digest.digest(key.toArray());
} else {
  key.append(format == FORMAT.CLIENT ? SERVER_MAGIC_CONFIDENTIALITY : CLIENT_MAGIC_CONFIDENTIALITY);
  hmacKey = digest.digest(key.toArray());
    throw saslDigest.mechUnknownCipher(cipher).toSaslException();
  ciph = Cipher.getInstance(transformationSpec.getTransformation());
  int slash = ciph.getAlgorithm().indexOf('/');
  String alg = (slash > -1 ? ciph.getAlgorithm().substring(0, slash) : ciph.getAlgorithm());
    cipherKey = new SecretKeySpec(cipherKeyBytes, alg);
  } else if (cipher.equals("des")) {
    cipherKeyBytes = Arrays.copyOf(hmacKey, 7); // first 7 bytes
    ciph.init((wrap ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE), cipherKey, new IvParameterSpec(IV), secureRandomGenerator);
  } else {
    ciph.init((wrap ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE), cipherKey, secureRandomGenerator);

代码示例来源: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: commonsguy/cw-omnibus

private void create(KeyStore ks, ObservableEmitter<char[]> emitter)
 throws Exception {
 SecureRandom rand=new SecureRandom();
 char[] passphrase=new char[128];
 for (int i=0; i<passphrase.length; i++) {
  passphrase[i]=BASE36_SYMBOLS.charAt(rand.nextInt(BASE36_SYMBOLS.length()));
 }
 createKey(ks, keyName, timeout);
 SecretKey secretKey=(SecretKey)ks.getKey(keyName, null);
 Cipher cipher=Cipher.getInstance("AES/CBC/PKCS7Padding");
 byte[] iv=new byte[BLOCK_SIZE];
 rand.nextBytes(iv);
 IvParameterSpec ivParams=new IvParameterSpec(iv);
 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParams);
 byte[] toEncrypt=toBytes(passphrase);
 byte[] encrypted=cipher.doFinal(toEncrypt);
 BufferedSink sink=Okio.buffer(Okio.sink(encryptedFile));
 sink.write(iv);
 sink.write(encrypted);
 sink.close();
 emitter.onNext(passphrase);
}

代码示例来源:origin: commonsguy/cw-omnibus

@Override
public void subscribe(ObservableEmitter<EncryptionResult> emitter)
 throws Exception {
 if (initException==null) {
  createKey(keyName, timeout);
  SecretKey secretKey=(SecretKey)ks.getKey(keyName, null);
  Cipher cipher=Cipher.getInstance("AES/CBC/PKCS7Padding");
  SecureRandom rand=new SecureRandom();
  byte[] iv=new byte[BLOCK_SIZE];
  rand.nextBytes(iv);
  IvParameterSpec ivParams=new IvParameterSpec(iv);
  cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParams);
  emitter.onNext(new EncryptionResult(ivParams.getIV(), cipher.doFinal(toEncrypt)));
 }
 else {
  throw initException;
 }
}

代码示例来源:origin: jenkinsci/jenkins

new SecureRandom().nextBytes(iv);
  jnlpMac = JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(slaveName.getBytes("UTF-8"));
SecretKey key = new SecretKeySpec(jnlpMac, 0, /* export restrictions */ 128 / 8, "AES");
byte[] encrypted;
try {
  Cipher c = Secret.getCipher("AES/CFB8/NoPadding");
  c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
  encrypted = c.doFinal(csos.getBytes());
} catch (GeneralSecurityException x) {
  throw new IOException(x);

代码示例来源: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: stackoverflow.com

SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
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: google/data-transfer-project

@Override
 public String encrypt(String data) {
  try {
   Cipher cipher = Cipher.getInstance(transformation);
   cipher.init(Cipher.ENCRYPT_MODE, key);
   byte[] salt = new byte[8];
   SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
   random.nextBytes(salt);
   cipher.update(salt);
   byte[] encrypted = cipher.doFinal(data.getBytes(Charsets.UTF_8));
   return BaseEncoding.base64Url().encode(encrypted);
  } catch (BadPaddingException
    | IllegalBlockSizeException
    | InvalidKeyException
    | NoSuchAlgorithmException
    | NoSuchPaddingException e) {
   monitor.severe(() -> format("Exception encrypting data, length: %s", data.length()), e);
   throw new RuntimeException(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);
}

相关文章