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

How to use
Key
in
java.security

Best Java code snippets using java.security.Key (Showing top 20 results out of 15,111)

Refine searchRefine arrow

  • Cipher
  • X509EncodedKeySpec
  • PKCS8EncodedKeySpec
  • KeyPair
  • KeyPairGenerator
  • SecureRandom
  • InvalidKeySpecException
  • KeyFactory
  • IvParameterSpec
origin: stackoverflow.com

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] encodedprivkey = keyPair.getPrivate().getEncoded();
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
byte[] ciphertext = pbeCipher.doFinal(encodedprivkey);
origin: aws/aws-sdk-java

if (materials.getKeyPair() != null) {
  kek = materials.getKeyPair().getPrivate();
  if (kek == null) {
    throw new SdkClientException("Key encrypting key not available");
      .getInstance(keyWrapAlgo) : Cipher.getInstance(
      keyWrapAlgo, securityProvider);
    cipher.init(Cipher.UNWRAP_MODE, kek);
    return (SecretKey) cipher.unwrap(cekSecured, keyWrapAlgo,
                     Cipher.SECRET_KEY);
    cipher = Cipher.getInstance(kek.getAlgorithm(),
                  securityProvider);
  } else {
    cipher = Cipher.getInstance(kek.getAlgorithm());
  cipher.init(Cipher.DECRYPT_MODE, kek);
origin: wildfly/wildfly

RawKey(Key original) {
  algorithm = original.getAlgorithm();
  format = original.getFormat();
  final byte[] encoded = original.getEncoded();
  this.encoded = encoded == null ? null : encoded.clone();
}
origin: google/guava

private static String hmacToString(String methodName, Key key) {
 return String.format(
   "Hashing.%s(Key[algorithm=%s, format=%s])",
   methodName, key.getAlgorithm(), key.getFormat());
}
origin: SonarSource/sonarqube

@Test
public void loadSecretKeyFromFile_trim_content() throws Exception {
 URL resource = getClass().getResource("/org/sonar/api/config/AesCipherTest/non_trimmed_secret_key.txt");
 String path = new File(resource.toURI()).getCanonicalPath();
 AesCipher cipher = new AesCipher(null);
 Key secretKey = cipher.loadSecretFileFromFile(path);
 assertThat(secretKey.getAlgorithm()).isEqualTo("AES");
 assertThat(secretKey.getEncoded().length).isGreaterThan(10);
}
origin: stackoverflow.com

 byte[] data = "test".getBytes("UTF8");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair keyPair = kpg.genKeyPair();

byte[] pk = keyPair.getPublic().getEncoded();
X509EncodedKeySpec spec = new X509EncodedKeySpec(pk);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(spec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encrypted = cipher.doFinal(data);

byte[] priv = keyPair.getPrivate().getEncoded();
PKCS8EncodedKeySpec spec2 = new PKCS8EncodedKeySpec(priv);
PrivateKey privKey = keyFactory.generatePrivate(spec2);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plain = cipher.doFinal(encrypted);

System.out.println(new String(plain, "UTF8")); //=> "test"
origin: stackoverflow.com

 KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
KeyPair pair = gen.generateKeyPair();
FileOutputStream ospvt = new FileOutputStream("pvt.der");
try {
 ospvt.write(pair.getPrivate().getEncoded());
 ospvt.flush();
} finally {
 ospvt.close();
}
FileOutputStream ospub = new FileOutputStream("pub.der");
try {
 ospub.write(pair.getPublic().getEncoded());
 ospub.flush();
} finally {
 ospub.close();
}
origin: stackoverflow.com

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);
PublicKey pub = pair.getPublic();
byte[] encoded = pub.getEncoded();
PublicKey fromEncoded = KeyFactory.getInstance("DSA", "SUN").generatePublic(new X509EncodedKeySpec(encoded));
dsa.initVerify(fromEncoded);
origin: aws/aws-sdk-java

if (materials.getKeyPair() != null) {
  kek = materials.getKeyPair().getPublic();
} else {
  if (keyWrapAlgo != null) {
    Cipher cipher = provider == null ? Cipher
      .getInstance(keyWrapAlgo) : Cipher.getInstance(
      keyWrapAlgo, provider);
    cipher.init(Cipher.WRAP_MODE, kek, srand);
    return new SecuredCEK(cipher.wrap(cek), keyWrapAlgo, matdesc);
  String algo = kek.getAlgorithm();
  if (provider != null) {
    cipher = Cipher.getInstance(algo, provider);
origin: stackoverflow.com

 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pub = keyPair.getPublic();
PrivateKey prv = keyPair.getPrivate();

byte[] pubBytes = pub.getEncoded();
byte[] prvBytes = prv.getEncoded();

// now save pubBytes or prvBytes

// to recover the key
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey prv_recovered = kf.generatePrivate(new PKCS8EncodedKeySpec(prvBytes));
PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pubBytes));

System.out.println("Private Key: \n" + prv_recovered.toString());
System.out.println("Public Key: \n" + pub_recovered.toString());
origin: stackoverflow.com

 DHParameterSpec dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH", "BC");
aliceKpairGen.initialize(dhSkipParamSpec);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();

aliceKeyAgree = KeyAgreement.getInstance("DH", "BC");
aliceKeyAgree.init(aliceKpair.getPrivate());


//... obtaining Bob's Public Key
aliceKeyFac = KeyFactory.getInstance("DH", "BC");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);

aliceKeyAgree.doPhase(bobPubKey, true);
SecretKey aliceAesKey = aliceKeyAgree.generateSecret("AES");

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, aliceAesKey);
byte[] cipherText = cipher.doFinal(plaintext.getBytes());
origin: apache/hbase

@Test
public void testWALKeyWrapping() throws Exception {
 // set up the key provider for testing to resolve a key for our test subject
 Configuration conf = new Configuration(); // we don't need HBaseConfiguration for this
 conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
 // generate a test key
 byte[] keyBytes = new byte[AES.KEY_LENGTH];
 new SecureRandom().nextBytes(keyBytes);
 String algorithm = conf.get(HConstants.CRYPTO_WAL_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
 Key key = new SecretKeySpec(keyBytes, algorithm);
 // wrap the test key
 byte[] wrappedKeyBytes = EncryptionUtil.wrapKey(conf, "hbase", key);
 assertNotNull(wrappedKeyBytes);
 // unwrap
 Key unwrappedKey = EncryptionUtil.unwrapWALKey(conf, "hbase", wrappedKeyBytes);
 assertNotNull(unwrappedKey);
 // only secretkeyspec supported for now
 assertTrue(unwrappedKey instanceof SecretKeySpec);
 // did we get back what we wrapped?
 assertTrue("Unwrapped key bytes do not match original",
  Bytes.equals(keyBytes, unwrappedKey.getEncoded()));
}
origin: apache/ignite

/** {@inheritDoc} */
@Override public byte[] decrypt(byte[] data, Serializable key) {
  assert key instanceof KeystoreEncryptionKey;
  ensureStarted();
  try {
    SecretKeySpec keySpec = new SecretKeySpec(((KeystoreEncryptionKey)key).key().getEncoded(), CIPHER_ALGO);
    Cipher cipher = aesWithPadding.get();
    cipher.init(DECRYPT_MODE, keySpec, new IvParameterSpec(data, 0, cipher.getBlockSize()));
    return cipher.doFinal(data, cipher.getBlockSize(), data.length - cipher.getBlockSize());
  }
  catch (InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException |
    BadPaddingException e) {
    throw new IgniteSpiException(e);
  }
}
origin: stackoverflow.com

 KeyGenerator kgenerator = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
kgenerator.init(128, random);
Key aeskey = kgenerator.generateKey();

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, random);
KeyPair kpa = kpg.genKeyPair();
PublicKey pubKey = kpa.getPublic();
PrivateKey privKey = kpa.getPrivate();    

// Encrypt the generated Symmetric AES Key using RSA cipher  
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");            
rsaCipher.init(Cipher.WRAP_MODE, pubKey);
byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);            
// RSA Decryption of Encrypted Symmetric AES key
rsaCipher.init(Cipher.UNWRAP_MODE, privKey);
Key decryptedKey = rsaCipher.unwrap(encryptedSymmKey, "AES", Cipher.SECRET_KEY);

System.out.println("Decrypted Key Length: " + decryptedKey.getEncoded().length * 8); // -> 128
origin: stackoverflow.com

 @Test
public void testKeyConversion() throws GeneralSecurityException {

  /* Generate random key pair */
  KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
  AlgorithmParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
  keyPairGenerator.initialize(spec, new SecureRandom());
  KeyPair keyPair = keyPairGenerator.generateKeyPair();

  /* Encode private key as PKCS#8 base64 string */
  byte[] privKeyBytes = keyPair.getPrivate().getEncoded();
  String privKeyStr = DatatypeConverter.printBase64Binary(privKeyBytes);

  /* Decode private key as PKCS#8 base64 string */
  byte[] privKeyBytes2 = DatatypeConverter.parseBase64Binary(privKeyStr);
  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes2);
  PrivateKey privateKey = keyFactory.generatePrivate(privSpec);

  /* Ensure key is the same */
  byte[] privKeyBytes3 = privateKey.getEncoded();
  assertEquals(
      DatatypeConverter.printHexBinary(privKeyBytes),
      DatatypeConverter.printHexBinary(privKeyBytes3));
}
origin: wildfly/wildfly

/** Encrypts the current secret key with the requester's public key (the requester will decrypt it with its private key) */
protected byte[] encryptSecretKey(Key secret_key, PublicKey public_key) throws Exception {
  Cipher tmp;
  if (provider != null && !provider.trim().isEmpty())
    tmp=Cipher.getInstance(asym_algorithm, provider);
  else
    tmp=Cipher.getInstance(asym_algorithm);
  tmp.init(Cipher.ENCRYPT_MODE, public_key);
  // encrypt current secret key
  return tmp.doFinal(secret_key.getEncoded());
}
origin: GlowstoneMC/Glowstone

  /**
   * Generates an X509 formatted key used in authentication.
   *
   * @param base The key to use to generate a public key from its key spec.
   * @return The X509 formatted key.
   */
  public static Key generateX509Key(Key base) {
    Key key = null;
    try {
      X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(base.getEncoded());
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");

      key = keyFactory.generatePublic(encodedKeySpec);
    } catch (Exception ex) {
      GlowServer.logger.log(Level.SEVERE, "Unable to generate X509 encoded key", ex);
    }
    return key;
  }
}
origin: plutext/docx4j

int keySizeInBytes = key.getEncoded().length;
if (padding == null) padding = "NoPadding";
  if (Cipher.getMaxAllowedKeyLength(cipherAlgorithm.jceId) < keySizeInBytes*8) {
    throw new EncryptedDocumentException("Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files");
    cipher = Cipher.getInstance(cipherAlgorithm.jceId);
  } else if (cipherAlgorithm.needsBouncyCastle) {
    registerBouncyCastle();
    cipher = Cipher.getInstance(cipherAlgorithm.jceId + "/" + chain.jceId + "/" + padding, "BC");
  } else {
    cipher = Cipher.getInstance(cipherAlgorithm.jceId + "/" + chain.jceId + "/" + padding);
    AlgorithmParameterSpec aps;
    if (cipherAlgorithm == CipherAlgorithm.rc2) {
      aps = new RC2ParameterSpec(key.getEncoded().length*8, vec);
    } else {
      aps = new IvParameterSpec(vec);
    cipher.init(cipherMode, key, aps);
origin: stackoverflow.com

public static String generateKeyPair() {
   try {
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
     kpg.initialize(2048, new SecureRandom());
     KeyPair pair = kpg.generateKeyPair();
     PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec(pair.getPrivate().getEncoded());
     StringBuilder sb = new StringBuilder();
     sb.append("-----BEGIN PRIVATE KEY-----");
     sb.append(new String(Base64.encode(keyspec.getEncoded())));
     sb.append("-----END PRIVATE KEY-----");
     return new String(Base64.encode(sb.toString().getBytes()));
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchProviderException e) {
     e.printStackTrace();
   }
   return null;
 }
origin: robovm/robovm

      return (T) (new PKCS8EncodedKeySpec(key.getEncoded()));
    throw new InvalidKeySpecException("'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec");
      return (T) (new X509EncodedKeySpec(key.getEncoded()));
    throw new InvalidKeySpecException("'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec");
throw new InvalidKeySpecException("'key' is neither DSAPublicKey nor DSAPrivateKey");
java.securityKey

Javadoc

Key is the common interface for all keys.

Most used methods

  • getEncoded
    Returns the key in its primary encoding format, or null if this key does not support encoding.
  • getAlgorithm
    Returns the standard algorithm name for this key. For example, "DSA" would indicate that this key is
  • getFormat
    Returns the name of the primary encoding format of this key, or null if this key does not support en
  • <init>

Popular in Java

  • Parsing JSON documents to java classes using gson
  • startActivity (Activity)
  • compareTo (BigDecimal)
  • getApplicationContext (Context)
  • HttpURLConnection (java.net)
    An URLConnection for HTTP (RFC 2616 [http://tools.ietf.org/html/rfc2616]) used to send and receive d
  • SocketException (java.net)
    This SocketException may be thrown during socket creation or setting options, and is the superclass
  • MessageDigest (java.security)
    Uses a one-way hash function to turn an arbitrary number of bytes into a fixed-length byte sequence.
  • Timestamp (java.sql)
    A Java representation of the SQL TIMESTAMP type. It provides the capability of representing the SQL
  • Iterator (java.util)
    An iterator over a sequence of objects, such as a collection.If a collection has been changed since
  • BlockingQueue (java.util.concurrent)
    A java.util.Queue that additionally supports operations that wait for the queue to become non-empty
  • Top Sublime Text 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