List of usage examples for javax.crypto KeyGenerator getInstance
public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2Test.java
@Test public void testAttributEncryptionSymmetric() throws Exception { // Setup/*from www .j a v a 2 s. co m*/ String algorithm = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128; KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key = kgen.generateKey(); Encrypter encrypter = Saml2Util.getEncrypter(algorithm, key); // Operate: encrypt EncryptedAttribute encTarget; XMLObject encObject = null; try { encObject = encrypter.encrypt(getAttribute()); } catch (EncryptionException e) { fail("Object encryption failed: " + e); } // Verify LOG.debug(Saml2Util.domToString(Saml2Util.marshall(encObject), true)); assertNotNull("Encrypted object was null", encObject); assertTrue("Encrypted object was not an instance of the expected type", encObject instanceof EncryptedAttribute); encTarget = (EncryptedAttribute) encObject; assertEquals("Type attribute", EncryptionConstants.TYPE_ELEMENT, encTarget.getEncryptedData().getType()); assertEquals("Algorithm attribute", algorithm, encTarget.getEncryptedData().getEncryptionMethod().getAlgorithm()); assertNotNull("KeyInfo", encTarget.getEncryptedData().getKeyInfo()); assertEquals("Number of EncryptedKeys", 0, encTarget.getEncryptedData().getKeyInfo().getEncryptedKeys().size()); assertFalse("EncryptedData ID attribute was empty", DatatypeHelper.isEmpty(encTarget.getEncryptedData().getID())); // Setup Decrypter decrypter = Saml2Util.getDecrypter(key); // Operate: decrypt SAMLObject decryptedTarget = null; try { decryptedTarget = decrypter.decrypt(encTarget); } catch (DecryptionException e) { fail("Error on decryption of encrypted SAML 2 type to element: " + e); } // Verify assertNotNull("Decrypted target was null", decryptedTarget); assertTrue("Decrypted target was not the expected type", decryptedTarget instanceof Attribute); LOG.debug(Saml2Util.domToString(Saml2Util.marshall(decryptedTarget), true)); }
From source file:org.apache.hadoop.security.AccessTokenHandler.java
/** Initialize access keys */ private synchronized void generateKeys() throws NoSuchAlgorithmException { keyGen = KeyGenerator.getInstance("HmacSHA1"); /*/*from w ww . j a va2 s .c o m*/ * Need to set estimated expiry dates for currentKey and nextKey so that if * NN crashes, DN can still expire those keys. NN will stop using the newly * generated currentKey after the first keyUpdateInterval, however it may * still be used by DN and Balancer to generate new tokens before they get a * chance to sync their keys with NN. Since we require keyUpdInterval to be * long enough so that all live DN's and Balancer will sync their keys with * NN at least once during the period, the estimated expiry date for * currentKey is set to now() + 2 * keyUpdateInterval + tokenLifetime. * Similarly, the estimated expiry date for nextKey is one keyUpdateInterval * more. */ serialNo++; currentKey = new AccessKey(serialNo, new Text(keyGen.generateKey().getEncoded()), System.currentTimeMillis() + 2 * keyUpdateInterval + tokenLifetime); serialNo++; nextKey = new AccessKey(serialNo, new Text(keyGen.generateKey().getEncoded()), System.currentTimeMillis() + 3 * keyUpdateInterval + tokenLifetime); allKeys.put(currentKey.getKeyID(), currentKey); allKeys.put(nextKey.getKeyID(), nextKey); }
From source file:org.wildfly.security.keystore.ModifyTrackingKeyStoreTest.java
private SecretKey getSecretKey() throws GeneralSecurityException { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128);/*ww w .j ava2 s . c om*/ return keyGen.generateKey(); }
From source file:org.sakaiproject.linktool.LinkToolUtil.java
/** * Generate a random salt, and write it to a file * //from w ww . ja va 2s. c om * @param dirname * writes to file saltname in this * directory. dirname assumed to end in / */ private static void gensalt(String dirname) { try { // Generate a key for the HMAC-SHA1 keyed-hashing algorithm KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA1"); SecretKey key = keyGen.generateKey(); writeKey(key, dirname + saltname); } catch (Exception e) { M_log.warn("Error generating salt", e); } }
From source file:com.bamboocloud.im.provisioner.json.crypto.simple.SimpleEncryptor.java
/** * Encrypts using an asymmetric cipher.// w w w.ja va 2 s. c om * * @param value the value to be encrypted. * @return the encrypted value. * @throws GeneralSecurityException if a cryptographic operation failed. * @throws IOException if an I/O exception occurred. */ private Object asymmetric(Object object) throws GeneralSecurityException, IOException { String symmetricCipher = "AES/ECB/PKCS5Padding"; // no IV required for randomly-generated session key KeyGenerator generator = KeyGenerator.getInstance("AES"); generator.init(128); SecretKey sessionKey = generator.generateKey(); Cipher symmetric = Cipher.getInstance(symmetricCipher); symmetric.init(Cipher.ENCRYPT_MODE, sessionKey); String data = Base64.encodeBase64String(symmetric.doFinal(mapper.writeValueAsBytes(object))); Cipher asymmetric = Cipher.getInstance(cipher); asymmetric.init(Cipher.ENCRYPT_MODE, key); HashMap<String, Object> keyObject = new HashMap<String, Object>(); keyObject.put("cipher", this.cipher); keyObject.put("key", this.alias); keyObject.put("data", Base64.encodeBase64String(asymmetric.doFinal(sessionKey.getEncoded()))); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("cipher", symmetricCipher); result.put("key", keyObject); result.put("data", data); return result; }
From source file:org.kuali.rice.core.impl.encryption.DemonstrationGradeEncryptionServiceImpl.java
/** * /* w ww . ja v a2 s. c o m*/ * This method generates keys. This method is implementation specific and should not be present in any general purpose interface * extracted from this class. * * @return * @throws Exception */ public static String generateEncodedKey() throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey desKey = keygen.generateKey(); // Create the cipher Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init((Cipher.WRAP_MODE), desKey); SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES"); DESKeySpec desSpec = (DESKeySpec) desFactory.getKeySpec(desKey, javax.crypto.spec.DESKeySpec.class); byte[] rawDesKey = desSpec.getKey(); return new String(Base64.encodeBase64(rawDesKey)); }
From source file:org.mozilla.android.sync.crypto.Cryptographer.java
/** * Make 2 random 256 bit keys (encryption and HMAC). * @return a KeyBundle// w w w. j a va2s.c o m * @throws CryptoException on error */ public static KeyBundle generateKeys() throws CryptoException { KeyGenerator keygen; try { keygen = KeyGenerator.getInstance(KEY_ALGORITHM_SPEC); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } keygen.init(KEY_SIZE); byte[] encryptionKey = keygen.generateKey().getEncoded(); byte[] hmacKey = keygen.generateKey().getEncoded(); return new KeyBundle(encryptionKey, hmacKey); }
From source file:org.sonar.api.config.AesCipher.java
String generateRandomSecretKey() { try {/*from w w w.j ava 2s .com*/ KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY); keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom()); SecretKey secretKey = keyGen.generateKey(); return new String(Base64.encodeBase64(secretKey.getEncoded())); } catch (Exception e) { throw new IllegalStateException("Fail to generate secret key", e); } }
From source file:org.apache.lucene.gdata.server.authentication.BlowfishAuthenticationController.java
/** * @see org.apache.lucene.gdata.server.authentication.AuthenticationController#initialize() *//*from w w w .j a va 2s. c o m*/ public void initialize() { if (this.key == null) throw new IllegalArgumentException("Auth key must not be null"); if (this.key.length() < 5 || this.key.length() > 16) throw new IllegalArgumentException("Auth key length must be greater than 4 and less than 17"); try { Provider sunJce = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sunJce); KeyGenerator kgen = KeyGenerator.getInstance(ALG); kgen.init(448); // 448 Bit^M byte[] raw = this.key.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, ALG); this.deCrypt = Cipher.getInstance(ALG); this.enCrypt = Cipher.getInstance(ALG); this.deCrypt.init(Cipher.DECRYPT_MODE, skeySpec); this.enCrypt.init(Cipher.ENCRYPT_MODE, skeySpec); } catch (Exception e) { throw new AuthenticatorException( "Can't initialize BlowfishAuthenticationController -- " + e.getMessage(), e); } calculateTimeOffset(); }
From source file:wssec.TestWSSecurityNew17.java
/** * Setup method// www.j a v a 2 s. c o m * <p/> * * @throws Exception Thrown when there is a problem in setup */ protected void setUp() throws Exception { AxisClient tmpEngine = new AxisClient(new NullProvider()); msgContext = new MessageContext(tmpEngine); message = getSOAPMessage(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); keyData = key.getEncoded(); }