List of usage examples for javax.crypto KeyGenerator getInstance
public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.apache.ws.security.message.EncryptionAlgorithmSuiteTest.java
@org.junit.Test public void testSymmetricEncryption() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128);/*w ww . j a v a2 s. com*/ SecretKey key = keyGen.generateKey(); byte[] keyData = key.getEncoded(); WSSecEncrypt builder = new WSSecEncrypt(); builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER); builder.setSymmetricKey(key); builder.setEncryptSymmKey(false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); Document encryptedDoc = builder.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { String outputString = XMLUtils.PrettyDocumentToString(encryptedDoc); LOG.debug(outputString); } byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData); String identifier = Base64.encode(encodedBytes); SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler(); secretKeyCallbackHandler.addSecretKey(identifier, keyData); Element securityHeader = WSSecurityUtil.getSecurityHeader(encryptedDoc, null); AlgorithmSuite algorithmSuite = createAlgorithmSuite(); WSSecurityEngine secEngine = new WSSecurityEngine(); RequestData data = new RequestData(); data.setDecCrypto(crypto); data.setCallbackHandler(secretKeyCallbackHandler); data.setAlgorithmSuite(algorithmSuite); algorithmSuite.addEncryptionMethod(WSConstants.AES_128); secEngine.processSecurityHeader(securityHeader, data); algorithmSuite.setMinimumSymmetricKeyLength(256); try { secEngine.processSecurityHeader(securityHeader, data); fail("Expected failure as a 128 bit key is not allowed"); } catch (WSSecurityException ex) { // expected } algorithmSuite.setMinimumSymmetricKeyLength(64); algorithmSuite.setMaximumSymmetricKeyLength(120); try { secEngine.processSecurityHeader(securityHeader, data); fail("Expected failure as a 128 bit key is not allowed"); } catch (WSSecurityException ex) { // expected } }
From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java
/** * Test encryption using a generated AES 128 bit key that is * encrypted using a AES 192 bit key. Then reverse using the KEK *//*www . j a v a 2s . c om*/ public void testAES128ElementAES192KWCipherUsingKEK() throws Exception { Document d = document(); // source Document ed = null; Document dd = null; Element e = (Element) d.getElementsByTagName(element()).item(index()); Element ee = null; String source = null; String target = null; if (haveISOPadding && haveKeyWraps) { source = toString(d); // Set up a Key Encryption Key byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes(); Key kek = new SecretKeySpec(bits192, "AES"); // Generate a traffic key KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128); Key key = keygen.generateKey(); cipher = XMLCipher.getInstance(XMLCipher.AES_192_KeyWrap); cipher.init(XMLCipher.WRAP_MODE, kek); EncryptedKey encryptedKey = cipher.encryptKey(d, key); // encrypt cipher = XMLCipher.getInstance(XMLCipher.AES_128); cipher.init(XMLCipher.ENCRYPT_MODE, key); EncryptedData builder = cipher.getEncryptedData(); KeyInfo builderKeyInfo = builder.getKeyInfo(); if (builderKeyInfo == null) { builderKeyInfo = new KeyInfo(d); builder.setKeyInfo(builderKeyInfo); } builderKeyInfo.add(encryptedKey); ed = cipher.doFinal(d, e); //decrypt key = null; ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0); cipher = XMLCipher.getInstance(XMLCipher.AES_128); cipher.init(XMLCipher.DECRYPT_MODE, null); cipher.setKEK(kek); dd = cipher.doFinal(ed, ee); target = toString(dd); Assert.assertEquals(source, target); } else { log.warn("Test testAES128ElementAES192KWCipherUsingKEK skipped as necessary algorithms not available"); } }
From source file:io.kodokojo.config.module.SecurityModule.java
private SecretKey generateAesKey() { try {/* w w w . ja v a2 s .c om*/ KeyGenerator kg = KeyGenerator.getInstance("AES"); return kg.generateKey(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Unable to get key generator for AES", e); } }
From source file:org.codice.ddf.configuration.migration.CipherUtils.java
/** * Creates a secret key and stores it in a file * * @param keyPath the path for storing the secret key * @throws MigrationException when an invalid key algorithm is used * @throws MigrationException when the key can not be written to a file * @throws NoSuchAlgorithmException when an invalid algorithm is used for the {@link KeyGenerator} * @return a {@link SecretKey}/*from w ww . j a v a2s . c o m*/ */ private SecretKey createSecretKey(Path keyPath) throws NoSuchAlgorithmException { KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(MigrationZipConstants.KEY_ALGORITHM); keyGenerator.init(128); secretKey = keyGenerator.generateKey(); char[] hexKey = encodeHex(secretKey.getEncoded()); writeStringToFile(keyPath.toFile(), String.valueOf(hexKey), Charsets.UTF_8); return secretKey; } catch (IOException e) { throw new MigrationException(String.format(MigrationZipConstants.FILE_IO_ERROR, keyPath, e)); } }
From source file:edu.stanford.junction.extra.Encryption.java
@Override public boolean beforeActivityCreate() { try {//from w ww. j a v a2 s .c o m KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey skey = kgen.generateKey(); mKey = skey.getEncoded(); init(); } catch (Exception e) { e.printStackTrace(); } return true; }
From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java
public void initSessionKey() throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(256, new SecureRandom()); sessionKey = kg.generateKey();// ww w . j a va2s .co m }
From source file:com.amazonaws.services.s3.internal.crypto.S3CryptoModuleBase.java
protected final SecretKey generateCEK() { KeyGenerator generator;/*from w ww. jav a2s . c o m*/ try { generator = KeyGenerator.getInstance(contentCryptoScheme.getKeyGeneratorAlgorithm()); generator.init(contentCryptoScheme.getKeyLengthInBits(), cryptoScheme.getSecureRandom()); return generator.generateKey(); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException("Unable to generate envelope symmetric key:" + e.getMessage(), e); } }
From source file:org.opensaml.xml.security.SecurityHelper.java
/** * Generates a random Java JCE symmetric Key object from the specified XML Encryption algorithm URI. * //from w ww.jav a 2 s . c om * @param algoURI The XML Encryption algorithm URI * @return a randomly-generated symmetric Key * @throws NoSuchAlgorithmException thrown if the specified algorithm is invalid * @throws KeyException thrown if the length of the key to generate could not be determined */ public static SecretKey generateSymmetricKey(String algoURI) throws NoSuchAlgorithmException, KeyException { String jceAlgorithmName = getKeyAlgorithmFromURI(algoURI); if (DatatypeHelper.isEmpty(jceAlgorithmName)) { log.error("Mapping from algorithm URI '" + algoURI + "' to key algorithm not available, key generation failed"); throw new NoSuchAlgorithmException("Algorithm URI'" + algoURI + "' is invalid for key generation"); } Integer keyLength = getKeyLengthFromURI(algoURI); if (keyLength == null) { log.error("Key length could not be determined from algorithm URI, can't generate key"); throw new KeyException("Key length not determinable from algorithm URI, could not generate new key"); } KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName); keyGenerator.init(keyLength); return keyGenerator.generateKey(); }
From source file:org.kuali.rice.krad.devtools.maintainablexml.EncryptionService.java
private SecretKey unwrapEncodedKeyOld(String key) throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey desKey = keygen.generateKey(); // Create the cipher Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init((Cipher.UNWRAP_MODE), desKey); byte[] bytes = Base64.decodeBase64(key.getBytes()); // If decoding was done with commons-codec 1.3 and the key not ended with '=' bytes[6] = 1;/*from www .j a v a 2 s.c om*/ bytes[7] = 1; SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES"); DESKeySpec keyspec = new DESKeySpec(bytes); SecretKey k = desFactory.generateSecret(keyspec); return k; }
From source file:net.sf.xfd.provider.PublicProvider.java
private static @Nullable Key getSalt(Context c) { if (cookieSalt == null) { synchronized (PublicProvider.class) { if (cookieSalt == null) { try { try (ObjectInputStream oos = new ObjectInputStream(c.openFileInput(COOKIE_FILE))) { cookieSalt = (Key) oos.readObject(); } catch (ClassNotFoundException | IOException e) { LogUtil.logCautiously("Unable to read key file, probably corrupted or missing", e); final File corrupted = c.getFileStreamPath(COOKIE_FILE); //noinspection ResultOfMethodCallIgnored corrupted.delete(); }/* www .java 2s.c om*/ if (cookieSalt != null) { return cookieSalt; } final KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA1"); keygen.init(COOKIE_SIZE * Byte.SIZE); cookieSalt = keygen.generateKey(); try (ObjectOutputStream oos = new ObjectOutputStream( c.openFileOutput(COOKIE_FILE, Context.MODE_PRIVATE))) { oos.writeObject(cookieSalt); } catch (IOException e) { LogUtil.logCautiously("Failed to save key file", e); return null; } } catch (NoSuchAlgorithmException e) { throw new AssertionError("failed to initialize hash functions", e); } } } } return cookieSalt; }