congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
KeyGenerator
Code IndexAdd Tabnine to your IDE (free)

How to use
KeyGenerator
in
javax.crypto

Best Java code snippets using javax.crypto.KeyGenerator (Showing top 20 results out of 3,870)

Refine searchRefine arrow

  • SecretKey
  • Cipher
  • SecureRandom
  • SecretKeySpec
  • IvParameterSpec
origin: shuzheng/zheng

try {
  KeyGenerator keygen = KeyGenerator.getInstance("AES");
  SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  random.setSeed(ENCODE_RULES.getBytes());
  keygen.init(128, random);
  SecretKey originalKey = keygen.generateKey();
  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: gocd/gocd

public static SecretKey generateAESKey() throws NoSuchAlgorithmException {
  KeyGenerator generator = KeyGenerator.getInstance("AES");
  generator.init(128); // The AES key size in number of bits
  return generator.generateKey();
}
origin: gocd/gocd

private byte[] generateKey() throws NoSuchAlgorithmException {
  KeyGenerator keygen = KeyGenerator.getInstance("AES");
  keygen.init(128);
  byte[] key = keygen.generateKey().getEncoded();
  return key;
}
origin: pentaho/pentaho-kettle

public static Key generateSingleKey() throws NoSuchAlgorithmException {
 Key key = KeyGenerator.getInstance( SINGLE_KEY_ALGORITHM ).generateKey();
 return key;
}
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: org.apache.logging.log4j/log4j-core

final Cipher ec = Cipher.getInstance(algorithm);
final byte[] bytes = new byte[16]; // initialization vector
final SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(bytes);
final KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
final IvParameterSpec algorithmParameterSpec = new IvParameterSpec(bytes);
ec.init(Cipher.ENCRYPT_MODE, generator.generateKey(), algorithmParameterSpec, secureRandom);
final byte[] raw = new byte[0];
final byte[] encrypted = ec.doFinal(raw);
final Cipher dc = Cipher.getInstance(algorithm);
dc.init(Cipher.DECRYPT_MODE, generator.generateKey(), algorithmParameterSpec, secureRandom);
dc.doFinal(encrypted);
fail("expected a javax.crypto.BadPaddingException");
origin: com.quhaodian.discover/discover-plug-alidayu

/**
 * AES加密
 * 
 * @param content
 *            待加密的内容
 * @param encryptKey
 *            加密密钥
 * @return 加密后的byte[]
 * @throws SecretException
 */
public static String aesEncrypt(byte[] content, byte[] encryptKey) throws SecretException {
  try {
    KeyGenerator kgen = KeyGenerator.getInstance(AES);
    kgen.init(new SecureRandom(encryptKey));
    IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey, AES), iv);
    return base64Encode(cipher.doFinal(content));
  } catch (Exception e) {
    throw new SecretException(e);
  }
}
 
origin: stackoverflow.com

 public static String encrypt(String in) throws Exception {
  String out = " ";
  // generate a key
  KeyGenerator keygen = KeyGenerator.getInstance("DES");
  keygen.init(56);
  byte[] key = keygen.generateKey().getEncoded();
  SecretKeySpec skeySpec = new SecretKeySpec(key, "DES");

  // build the initialization vector
  SecureRandom random = new SecureRandom();
  byte iv[] = new byte[8]; //generate random 8 byte IV. 
  random.nextBytes(iv);
  IvParameterSpec ivspec = new IvParameterSpec(iv);
  // initialize the cipher for encrypt mode
  Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);

  byte[] encrypted = cipher.doFinal(in.getBytes());

  out = asHex(encrypted);

  return out;
}
origin: apache/incubator-dubbo

SignatureOutputStream(Hessian2Output out)
    throws IOException {
  try {
    KeyGenerator keyGen = KeyGenerator.getInstance(_algorithm);
      keyGen.init(_secureRandom);
    SecretKey sharedKey = keyGen.generateKey();
    Cipher keyCipher = Cipher.getInstance(keyAlgorithm);
    keyCipher.init(Cipher.WRAP_MODE, _privateKey);
    byte[] encKey = keyCipher.wrap(sharedKey);
origin: stackoverflow.com

try {
  KeyGenerator gen = KeyGenerator.getInstance("AES");
  gen.init(128);
  SecretKey key = gen.generateKey();
  byte[] keyBytes = key.getEncoded();
  System.out.print("Ge nyckeln ett filnamn: ");
  String filename = scan.next();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv);
  ecipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv);
c.init(Cipher.DECRYPT_MODE, keySpec, ivspec);
origin: stackoverflow.com

 // 1. Generate a session key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128)
SecretKey sessionKey = keyGen.generateKey();

// 2. Encrypt the session key with the RSA public key
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey)
byte[] encryptedSessionKey = rsaCipher.doFinal(sessionKey.getEncoded());

// 3. Encrypt the data using the session key (unencrypted)
Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, sessionKey); <-- sessionKey is the unencrypted
//                                                   session key.
// ... use aesCipher to encrypt your data

// 4. Save the encrypted data along with the encrypted 
// session key (encryptedSessionKey).
// PLEASE NOTE THAT BECAUSE OF THE ENCRYPTION MODE (CBC),
// YOU ALSO NEED TO ALSO SAVE THE IV (INITIALIZATION VECTOR).
// aesCipher.aesCipher.getParameters().
//     getParametersSpec(IvParameters.class).getIV();
origin: apache/usergrid

  private static byte[] getRawKey( byte[] seed ) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance( "AES" );
    SecureRandom sr = SecureRandom.getInstance( "SHA1PRNG" );
    sr.setSeed( seed );
    keyGenerator.init( 128, sr ); // 192 and 256 bits may not be available
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
  }
}
origin: stackoverflow.com

 Key privateKey = keyStore.getKey("youralias", "password".toCharArray());
PublicKey publicKey = keyStore.getCertificate("youralias").getPublicKey();

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
Key secKey = keyGen.generateKey();

Cipher keyCipher = Cipher.getInstance("RSA");
keyCipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encryptedKey = keyCipher.doFinal(secKey.getEncoded());

// Write & Read to/from file!

Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decryptedKey = decryptCipher.doFinal(encryptedKey);

boolean equals = Arrays.equals(secKey.getEncoded(), new SecretKeySpec(decryptedKey, "AES").getEncoded());
System.out.println(equals?"Successfull!":"Failed!");
origin: stackoverflow.com

 //Generate a key
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
SecretKey Key = KeyGen.generateKey();

//Generate init vector
SecureRandom rng = SecureRandom.getInstance("SHA1PRNG");
byte [] IV = new byte[16];
rng.nextBytes(IV);

//Initialize the encryptor
Cipher ci = Cipher.getInstance("AES/CBC/NoPadding"); //The spec might be different!
ci.init(Cipher.ENCRYPT_MODE, Key, new IvParameterSpec(IV));
origin: stackoverflow.com

 KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom sec = new SecureRandom(key.getBytes());
keygen.init(128, sec);
Key key = keygen.generateKey();
SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), "AES");
...
origin: stackoverflow.com

 public static void main(String... args) throws Exception {
  byte[] data = "hello".getBytes();

  KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
  keyGenerator.init(128); // 192 and 256 bits may not be available

  SecretKey secretKey = keyGenerator.generateKey();

  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

  // By initializing the cipher in CBC mode, an "initialization vector" has been randomly
  // generated. This initialization vector will be necessary to decrypt the encrypted data.
  // It is safe to store the initialization vector in plain text for later use. You can obtain
  // it's bytes by calling iv.getIV().
  cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  IvParameterSpec iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class);
  byte[] encryptedData = cipher.doFinal(data);

  // When decrypting the encrypted data, you must provide the initialization vector used
  // during the encryption phase.
  cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
  byte[] decryptedData = cipher.doFinal(encryptedData);

  if (!Arrays.equals(data, decryptedData)) {
    throw new Exception("Data was not decrypted successfully");
  }
}
origin: apache/pulsar

  cipher = Cipher.getInstance(AESGCM, BouncyCastleProvider.PROVIDER_NAME);
    return;
  keyGenerator = KeyGenerator.getInstance("AES");
  int aesKeyLength = Cipher.getMaxAllowedKeyLength("AES");
  if (aesKeyLength <= 128) {
    log.warn(
        "{} AES Cryptographic strength is limited to {} bits. Consider installing JCE Unlimited Strength Jurisdiction Policy Files.",
        logCtx, aesKeyLength);
    keyGenerator.init(aesKeyLength, secureRandom);
  } else {
    keyGenerator.init(256, secureRandom);
dataKey = keyGenerator.generateKey();
origin: Microsoft/AppCenter-SDK-Android

  @Test
  public void coverDefaultCipherParameterPassing() throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);
    SecretKey secretKey = keyGenerator.generateKey();
    String algorithm = "AES/CBC/PKCS5Padding";
    Cipher cipherTmp = Cipher.getInstance(algorithm);
    String provider = cipherTmp.getProvider().getName();
    CryptoUtils.ICipher encryptCipher = CryptoUtils.DEFAULT_CRYPTO_FACTORY.getCipher(algorithm, provider);
    assertEquals(algorithm, encryptCipher.getAlgorithm());
    assertEquals(provider, encryptCipher.getProvider());
    encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] data = encryptCipher.doFinal("test".getBytes(CHARSET));
    CryptoUtils.ICipher decryptCipher = CryptoUtils.DEFAULT_CRYPTO_FACTORY.getCipher(algorithm, provider);
    decryptCipher.init(DECRYPT_MODE, secretKey, new IvParameterSpec(encryptCipher.getIV()));
    assertEquals("test", new String(decryptCipher.doFinal(data), CHARSET));
    assertEquals("test", new String(decryptCipher.doFinal(data, 0, data.length), CHARSET));
    assertEquals(decryptCipher.getIV().length, decryptCipher.getBlockSize());
  }
}
origin: stackoverflow.com

SecretKey myDesKey = keygenerator.generateKey();
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = desCipher.doFinal(text);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
origin: org.connid/connid-framework-internal

public EncryptorImpl( boolean defaultKey ) {
  if ( defaultKey ) {
    _key = new SecretKeySpec(_defaultKeyBytes,ALGORITHM);
    _iv  = new IvParameterSpec(_defaultIvBytes);            
  }
  else {
    try {
      _key = KeyGenerator.getInstance(ALGORITHM).generateKey();
      _iv  = new IvParameterSpec(_defaultIvBytes);
    }
    catch (RuntimeException e) {
      throw e;
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}
javax.cryptoKeyGenerator

Javadoc

This class provides the public API for generating symmetric cryptographic keys.

Most used methods

  • getInstance
    Creates a new KeyGenerator instance that provides the specified key algorithm from the specified pro
  • generateKey
    Generates a secret key.
  • init
    Initializes this KeyGenerator instance with the specified algorithm parameters and randomness source
  • getProvider
    Returns the provider of this KeyGenerator instance.
  • <init>
    Creates a new KeyGenerator instance.
  • getAlgorithm
    Returns the name of the key generation algorithm.
  • initialize

Popular in Java

  • Making http requests using okhttp
  • addToBackStack (FragmentTransaction)
  • putExtra (Intent)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • FileNotFoundException (java.io)
    Thrown when a file specified by a program cannot be found.
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • Calendar (java.util)
    Calendar is an abstract base class for converting between a Date object and a set of integer fields
  • Collectors (java.util.stream)
  • Logger (org.apache.log4j)
    This is the central class in the log4j package. Most logging operations, except configuration, are d
  • Join (org.hibernate.mapping)
  • Best plugins for Eclipse
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