Tabnine Logo
Cipher
Code IndexAdd Tabnine to your IDE (free)

How to use
Cipher
in
javax.crypto

Best Java code snippets using javax.crypto.Cipher (Showing top 20 results out of 12,663)

Refine searchRefine arrow

  • SecretKeySpec
  • IvParameterSpec
  • SecretKeyFactory
  • PBEKeySpec
  • SecretKey
  • SecureRandom
  • MessageDigest
  • PBEParameterSpec
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);
}
javax.cryptoCipher

Javadoc

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.

Most used methods

  • init
    Initializes this cipher instance with the public key from the specified certificate and a source of
  • getInstance
    Creates a new cipher for the specified transformation.
  • doFinal
    Finishes a multi-part transformation (encryption or decryption). Processes the inputLen bytes in inp
  • update
    Continues a multi-part transformation (encryption or decryption). The transformed bytes are stored i
  • getBlockSize
    Returns this ciphers block size (in bytes).
  • getIV
    Returns the initialization vector for this cipher instance.
  • getMaxAllowedKeyLength
    Returns the maximum key length for the specified transformation.
  • getParameters
    Returns the parameters that where used to create this cipher instance. These may be a the same param
  • getOutputSize
    Returns the length in bytes an output buffer needs to be when this cipher is updated with inputLen b
  • wrap
    Wraps a key using this cipher instance.
  • unwrap
    Unwraps a key using this cipher instance.
  • getAlgorithm
    Returns the name of the algorithm of this cipher instance. This is the name of the transformation ar
  • unwrap,
  • getAlgorithm,
  • getProvider,
  • updateAAD,
  • <init>,
  • checkInputOffsetAndCount,
  • checkMode,
  • checkTransformation,
  • getCipher,
  • invalidTransformation

Popular in Java

  • Start an intent from android
  • getResourceAsStream (ClassLoader)
  • runOnUiThread (Activity)
  • scheduleAtFixedRate (Timer)
  • PrintStream (java.io)
    Fake signature of an existing Java class.
  • DateFormat (java.text)
    Formats or parses dates and times.This class provides factories for obtaining instances configured f
  • Arrays (java.util)
    This class contains various methods for manipulating arrays (such as sorting and searching). This cl
  • Dictionary (java.util)
    Note: Do not use this class since it is obsolete. Please use the Map interface for new implementatio
  • Collectors (java.util.stream)
  • Filter (javax.servlet)
    A filter is an object that performs filtering tasks on either the request to a resource (a servlet o
  • Top PhpStorm plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now