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

How to use
SecretKey
in
javax.crypto

Best Java code snippets using javax.crypto.SecretKey (Showing top 20 results out of 5,373)

Refine searchRefine arrow

  • SecretKeySpec
  • Cipher
  • KeyGenerator
  • PBEKeySpec
  • SecretKeyFactory
  • IvParameterSpec
  • SecureRandom
origin: geoserver/geoserver

kgen = KeyGenerator.getInstance("AES");
kgen.init(256);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
cipher.doFinal("This is just an example".getBytes());
strongEncryptionAvaialble = true;
LOGGER.info("Strong cryptography is available");
origin: org.apache.poi/poi

  @Override
  public Encryptor clone() throws CloneNotSupportedException {
    Encryptor other = (Encryptor)super.clone();
    other.secretKey = new SecretKeySpec(secretKey.getEncoded(), secretKey.getAlgorithm());
    // encryptionInfo is set from outside
    return other;
  }
}
origin: syncany/syncany

@Override
public String getFormat() {
  return secretKey.getFormat();
}
origin: oracle/helidon

static Cipher cipher(char[] masterPassword, byte[] salt, int cipherMode) throws HttpAuthException {
  try {
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec keySpec = new PBEKeySpec(masterPassword, salt, 10000, 128);
    SecretKeySpec spec = new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(cipherMode, spec, new IvParameterSpec(salt));
    return cipher;
  } catch (Exception e) {
    throw new HttpAuthException("Failed to prepare a cipher instance", e);
  }
}
origin: plantuml/plantuml

public static byte[] salting(String pass, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
  final int iterations = 500;
  final int keyLength = 512;
  final SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
  final PBEKeySpec spec = new PBEKeySpec(pass.toCharArray(), salt, iterations, keyLength);
  final SecretKey key = skf.generateSecret(spec);
  final byte[] tmp = key.getEncoded();
  return tmp;
}
origin: gocd/gocd

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

  rsaCipher = Cipher.getInstance("RSA"); // NON-NLS
} catch (GeneralSecurityException ex) {
  ConsoleMessages.Error.Net.Crypt.RSA_INIT_FAILED.log(ex);
  rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
  sharedSecret = new SecretKeySpec(rsaCipher.doFinal(message.getSharedSecret()),
      "AES"); // NON-NLS
} catch (Exception ex) {
  MessageDigest digest = MessageDigest.getInstance("SHA-1");
  digest.update(session.getSessionId().getBytes());
  digest.update(sharedSecret.getEncoded());
  digest.update(session.getServer().getKeyPair().getPublic().getEncoded());
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: org.elasticsearch/elasticsearch

private Cipher createCipher(int opmode, char[] password, byte[] salt, byte[] iv) throws GeneralSecurityException {
  PBEKeySpec keySpec = new PBEKeySpec(password, salt, KDF_ITERS, CIPHER_KEY_BITS);
  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KDF_ALGO);
  SecretKey secretKey = keyFactory.generateSecret(keySpec);
  SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), CIPHER_ALGO);
  GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_BITS, iv);
  Cipher cipher = Cipher.getInstance(CIPHER_ALGO + "/" + CIPHER_MODE + "/" + CIPHER_PADDING);
  cipher.init(opmode, secret, spec);
  cipher.updateAAD(salt);
  return cipher;
}
origin: org.apache.poi/poi

protected static Cipher initCipherForBlock(Cipher cipher, int block,
  EncryptionInfo encryptionInfo, SecretKey skey, int encryptMode)
throws GeneralSecurityException {
  EncryptionVerifier ver = encryptionInfo.getVerifier();
  HashAlgorithm hashAlgo = ver.getHashAlgorithm();
  byte blockKey[] = new byte[4];
  LittleEndian.putUInt(blockKey, 0, block);
  byte encKey[] = CryptoFunctions.generateKey(skey.getEncoded(), hashAlgo, blockKey, 16);
  SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm());
  if (cipher == null) {
    EncryptionHeader em = encryptionInfo.getHeader();
    cipher = CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), null, null, encryptMode);
  } else {
    cipher.init(encryptMode, key);
  }
  return cipher;
}
origin: jenkinsci/jenkins

/**
 * @param keyLength
 *      Block size of the asymmetric cipher, in bits. I thought I can get it from {@code asym.getBlockSize()}
 *      but that doesn't work with Sun's implementation.
 */
public CombinedCipherInputStream(InputStream in, Cipher asym, String algorithm, int keyLength) throws IOException, GeneralSecurityException {
  super(in);
  String keyAlgorithm = getKeyAlgorithm(algorithm);
  // first read the symmetric key cipher
  byte[] symKeyBytes = new byte[keyLength/8];
  new DataInputStream(in).readFully(symKeyBytes);
  SecretKey symKey = new SecretKeySpec(asym.doFinal(symKeyBytes),keyAlgorithm);
  // the rest of the data will be decrypted by this symmetric cipher
  Cipher sym = Secret.getCipher(algorithm);
  sym.init(Cipher.DECRYPT_MODE,symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded()));
  super.in = new CipherInputStream(in,sym);
}
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: 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

 ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object   
byte[] b = baos.toByteArray();  

byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();    

// encrypt
byte[] encryptedData = encrypt(key,b);
// decrypt
byte[] decryptedData = decrypt(key,encryptedData);
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: wildfly/wildfly

private void saveSecretKey(String ksAlias, ObjectOutputStream oos, KeyStore.SecretKeyEntry entry) throws IOException, GeneralSecurityException {
  ByteArrayOutputStream entryData = new ByteArrayOutputStream(1024);
  ObjectOutputStream entryOos = new ObjectOutputStream(entryData);
  entryOos.writeUTF(ksAlias);
  writeBytes(entry.getSecretKey().getEncoded(), entryOos);
  entryOos.flush();
  encrypt.init(Cipher.ENCRYPT_MODE, storageSecretKey, (AlgorithmParameterSpec) null); // ELY-1308: third param need to workaround BouncyCastle bug
  int blockSize = encrypt.getBlockSize();
  if (blockSize == 0) throw log.algorithmNotBlockBased(encrypt.getAlgorithm());
  Assert.checkMaximumParameter("cipher block size", 256, blockSize);
  byte[] padded = pkcs7Pad(entryData.toByteArray(), blockSize);
  byte[] encrypted = encrypt.doFinal(padded);
  byte[] iv = encrypt.getIV();
  if (iv == null) throw log.algorithmNotIV(encrypt.getAlgorithm());
  oos.writeInt(SECRET_KEY_ENTRY_TYPE);
  writeBytes(encrypted, oos);
  writeBytes(iv, oos);
}
origin: kaaproject/kaa

/**
 * Gets the encoded session key.
 *
 * @return the encoded session key
 * @throws GeneralSecurityException the general security exception
 */
public byte[] getEncodedSessionKey() throws GeneralSecurityException {
 SecretKey key = getSessionKey();
 Cipher keyCipher = RSA_CIPHER.get();
 keyCipher.init(Cipher.ENCRYPT_MODE, remotePublicKey);
 return keyCipher.doFinal(key.getEncoded());
}
origin: plutext/docx4j

protected static Cipher initCipherForBlock(Cipher existing, int block, boolean lastChunk, EncryptionInfoBuilder builder, SecretKey skey, int encryptionMode)
throws GeneralSecurityException {
  
  EncryptionHeader header = builder.getHeader();
  if (existing == null || lastChunk) {
    String padding = (lastChunk ? "PKCS5Padding" : "NoPadding");
    existing = getCipher(skey, header.getCipherAlgorithm(), header.getChainingMode(), 
        header.getKeySalt(), encryptionMode, padding);
  }
  byte[] blockKey = new byte[4];
  LittleEndian.putInt(blockKey, 0, block);
  byte[] iv = generateIv(header.getHashAlgorithmEx(), header.getKeySalt(), blockKey, header.getBlockSize());
  AlgorithmParameterSpec aps;
  if (header.getCipherAlgorithm() == CipherAlgorithm.rc2) {
    aps = new RC2ParameterSpec(skey.getEncoded().length*8, iv);
  } else {
    aps = new IvParameterSpec(iv);
  }
    
  existing.init(encryptionMode, skey, aps);
  
  return existing;
}
origin: jenkinsci/jenkins

private SecretKey getKey() {
  if (key==null) {
    synchronized (this) {
      if (key==null) {
        try {
          byte[] encoded = load();
          if (encoded==null) {
            KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
            SecretKey key = kg.generateKey();
            store(encoded=key.getEncoded());
          }
          key = new SecretKeySpec(encoded,ALGORITHM);
        } catch (IOException e) {
          throw new Error("Failed to load the key: "+getId(),e);
        } catch (NoSuchAlgorithmException e) {
          throw new Error("Failed to load the key: "+getId(),e);
        }
      }
    }
  }
  return key;
}
origin: spring-projects/spring-security

public AesBytesEncryptor(String password, CharSequence salt,
    BytesKeyGenerator ivGenerator, CipherAlgorithm alg) {
  PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), Hex.decode(salt),
      1024, 256);
  SecretKey secretKey = newSecretKey("PBKDF2WithHmacSHA1", keySpec);
  this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES");
  this.alg = alg;
  this.encryptor = alg.createCipher();
  this.decryptor = alg.createCipher();
  this.ivGenerator = ivGenerator != null ? ivGenerator : alg.defaultIvGenerator();
}
javax.cryptoSecretKey

Javadoc

A cryptographic secret (symmetric) key.

This interface is a marker interface to group secret keys and to provide type safety for.

Implementations of this interface have to overwrite the Object#equals(Object) and Object#hashCode()from java.lang.Object so comparison is done using the actual key data and not the object reference.

Most used methods

  • getEncoded
  • getAlgorithm
  • getFormat
  • destroy
  • isDestroyed

Popular in Java

  • Creating JSON documents from java classes using gson
  • onCreateOptionsMenu (Activity)
  • getExternalFilesDir (Context)
  • runOnUiThread (Activity)
  • BorderLayout (java.awt)
    A border layout lays out a container, arranging and resizing its components to fit in five regions:
  • Timer (java.util)
    Timers schedule one-shot or recurring TimerTask for execution. Prefer java.util.concurrent.Scheduled
  • Collectors (java.util.stream)
  • IOUtils (org.apache.commons.io)
    General IO stream manipulation utilities. This class provides static utility methods for input/outpu
  • Logger (org.apache.log4j)
    This is the central class in the log4j package. Most logging operations, except configuration, are d
  • SAXParseException (org.xml.sax)
    Encapsulate an XML parse error or warning.> This module, both source code and documentation, is in t
  • Top Vim 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