List of usage examples for javax.crypto KeyGenerator init
public final void init(int keysize)
From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java
protected SecretKey stateKey() { // only generate the state encrpytion key if the HTTP session is going // to be used for nonance checking as well. if (!oidcProvider.isCheckNonce()) { try {//from w w w. j a v a2 s .c o m if (oidcProvider.getClientSecret() != null && !oidcProvider.getClientSecret().isEmpty()) { byte[] key = oidcProvider.getClientSecret().getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); return secretKeySpec; } else { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); return keyGenerator.generateKey(); } } catch (Exception e) { LOG.log(Level.SEVERE, "", e); return null; } } return null; }
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 *//*from www . ja v a2s. c o m*/ 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:org.apache.xml.security.test.encryption.XMLCipherTester.java
/** * Test encryption using a generated AES 256 bit key that is * encrypted using an RSA key. Reverse using KEK *///from ww w . j a v a2s.c om public void testAES128ElementRSAKWCipherUsingKEK() 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) { source = toString(d); // Generate an RSA key KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA"); KeyPair kp = rsaKeygen.generateKeyPair(); PrivateKey priv = kp.getPrivate(); PublicKey pub = kp.getPublic(); // Generate a traffic key KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(256); Key key = keygen.generateKey(); cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5); cipher.init(XMLCipher.WRAP_MODE, pub); EncryptedKey encryptedKey = cipher.encryptKey(d, key); // encrypt cipher = XMLCipher.getInstance(XMLCipher.AES_256); 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); log.debug("Encrypted document"); log.debug(toString(ed)); //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(priv); dd = cipher.doFinal(ed, ee); target = toString(dd); log.debug("Output document"); log.debug(target); Assert.assertEquals(source, target); } else { log.warn("Test testAES128ElementRSAKWCipherUsingKEK skipped as necessary algorithms not available"); } }
From source file:org.apache.ws.security.message.WSSecEncrypt.java
private KeyGenerator getKeyGenerator() throws WSSecurityException { try {//from w w w . j a v a2 s . c o m // // Assume AES as default, so initialize it // String keyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(symEncAlgo); KeyGenerator keyGen = KeyGenerator.getInstance(keyAlgorithm); if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_128)) { keyGen.init(128); } else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_192)) { keyGen.init(192); } else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_256)) { keyGen.init(256); } return keyGen; } catch (NoSuchAlgorithmException e) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e); } }
From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java
/** * Test encryption using a generated AES 192 bit key that is * encrypted using a 3DES key. Then reverse by decrypting * EncryptedKey by hand/*ww w . j av a 2s . c om*/ */ public void testAES192ElementAES256KWCipher() 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(); DESedeKeySpec keySpec = new DESedeKeySpec(bits192); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); Key kek = keyFactory.generateSecret(keySpec); // Generate a traffic key KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(192); Key key = keygen.generateKey(); cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap); cipher.init(XMLCipher.WRAP_MODE, kek); EncryptedKey encryptedKey = cipher.encryptKey(d, key); // encrypt cipher = XMLCipher.getInstance(XMLCipher.AES_192); 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(); cipher.init(XMLCipher.DECRYPT_MODE, null); EncryptedData encryptedData = cipher.loadEncryptedData(ed, ee); if (encryptedData == null) { System.out.println("ed is null"); } else if (encryptedData.getKeyInfo() == null) { System.out.println("ki is null"); } EncryptedKey ek = encryptedData.getKeyInfo().itemEncryptedKey(0); if (ek != null) { XMLCipher keyCipher = XMLCipher.getInstance(); keyCipher.init(XMLCipher.UNWRAP_MODE, kek); key = keyCipher.decryptKey(ek, encryptedData.getEncryptionMethod().getAlgorithm()); } // Create a new cipher just to be paranoid XMLCipher cipher3 = XMLCipher.getInstance(); cipher3.init(XMLCipher.DECRYPT_MODE, key); dd = cipher3.doFinal(ed, ee); target = toString(dd); Assert.assertEquals(source, target); } else { log.warn("Test testAES192ElementAES256KWCipher skipped as necessary algorithms not available"); } }
From source file:org.warlock.itk.distributionenvelope.Payload.java
/** * Common payload content encryption method which is called after sanity * checks, and after any content signing is performed. * //w w w . ja va 2 s.c o m * @throws Exception */ private void doEncryption() throws Exception { // Make the one-time symmetric key, and encrypt the payload content using it. KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(AESKEYSIZE); SecretKey key = kgen.generateKey(); String cipherData = doAESEncryption(key); // Start constructing the XML Encryption "EncryptedData" element. The main // payload encryption is AES-256/CBC // StringBuilder sb = new StringBuilder( "<xenc:EncryptedData xmlns:xenc=\"http://www.w3.org/2001/04/xmlenc#\">"); sb.append("<xenc:EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#aes256-cbc\"/>"); // And then the KeyInfo which is the symmetric key byte[] encrypted for each // reader certificate. // sb.append("<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">"); byte[] keyMaterial = key.getEncoded(); for (X509Certificate x : readerCerts) { sb.append(doRSASymmetricKeyEncryption(x, keyMaterial)); } sb.append("</ds:KeyInfo>"); sb.append(cipherData); sb.append("</xenc:EncryptedData>"); // Set the payloadBody to the EncryptedData, and the "encrypted" flag to "true". // Note that "base64" and "compressed" apply to the *cleartext*, and so are not // altered by this operation. The same goes for the mime type. Receiving systems // that decrypt the payload will need these other data set correctly in order to // convert the encrypted and possibly otherwise-processed content into something // they can use. // payloadBody = sb.toString(); encrypted = true; // Make sure we overwrite the key byte[] before we leave, and mark the // one-time secret key null. // for (int i = 0; i < keyMaterial.length; i++) { keyMaterial[i] = 0; } key = null; }
From source file:org.apache.rampart.util.RampartUtil.java
public static KeyGenerator getEncryptionKeyGenerator(String symEncrAlgo) throws WSSecurityException { KeyGenerator keyGen; try {//from w w w. j av a2 s . c o m /* * Assume AES as default, so initialize it */ keyGen = KeyGenerator.getInstance("AES"); if (symEncrAlgo.equalsIgnoreCase(WSConstants.TRIPLE_DES)) { keyGen = KeyGenerator.getInstance("DESede"); } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_128)) { keyGen.init(128); } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_192)) { keyGen.init(192); } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_256)) { keyGen.init(256); } else { return null; } } catch (NoSuchAlgorithmException e) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e); } return keyGen; }
From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java
@Test public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception { // create AES shared key cipher Security.addProvider(new BouncyCastleProvider()); KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC"); kgen.init(128); SecretKey key = kgen.generateKey(); byte[] aesKey = key.getEncoded(); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "false"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("websocket.crypto.enabled", "true"); properties.put("websocket.crypto.cipherProvider", "BC"); properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding"); properties.put("websocket.crypto.secretKeyAlgorithm", "AES"); properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey)); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestWebSocketService.class); WebSocketClient wsClient = new WebSocketClient(); try {//from w w w. ja v a2 s .co m context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); messageRegistry.registerType("stuff", TestObject.class); wsClient.start(); QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, context.getBean(WebSocketPskFrameProcessor.class)); Session session = wsClient.connect(webSocket, new URI( "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())) .get(5000, TimeUnit.MILLISECONDS); Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null); byte[] rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); byte[] rawStuff = serDe.serialize(new TestObject("more stuff")); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); envelope = new Envelope("getStuff", null, null, null); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100))); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code); envelope = new Envelope("expectedError", null, null, null); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description); envelope = new Envelope("unexpectedError", null, null, null); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code); } finally { try { wsClient.stop(); } finally { context.close(); } } }
From source file:it.scoppelletti.programmerpower.security.CryptoUtils.java
/** * Restituisce un generatore di chiavi simmetriche. * //from www . j a va 2 s . co m * <H4>1. Proprietà</H4> * * <P><TABLE WIDTH="100%" BORDER="1" CELLPADDING="5"> * <THEAD> * <TR> * <TH>Proprietà</TH> * <TH>Descrizione</TH> * </TR> * </THEAD> * <TBODY> * <TR> * <TD>{@code alg}</TD> * <TD>Codice dell’algoritmo di crittografia.</TD> * </TR> * <TR> * <TD>{@code param.factory}</TD> * <TD>Nome della classe di factory dei parametri specifici * dell’algoritmo; la classe deve implementare * l’interfaccia {@code AlgorithmParameterSpecFactory} e * può prevedere altre proprietà.</TD> * </TR> * <TR> * <TD>{@code param.factory.prefix}</TD> * <TD>Eventuale prefisso da applicare al nome delle proprietà * interrogate dal provider {@code param.factory}.</TD> * </TR> * <TR> * <TD>{@code key.size}</TD> * <TD>Dimensione della chiave (numero di bit).</TD> * </TR> * <TR> * <TD COLSPAN="2">Le proprietà {@code param.factory} e * {@code key.size} non possono essere entrambe impostate; se nessuna * delle due proprietà è impostata, il generatore * sarà inizializzato con i parametri di default definiti dallo * specifico provider JCA.</TD> * </TR> * </TBODY> * </TABLE></P> * * @param props Proprietà. * @param prefix Prefisso da applicare al nome delle proprietà da * interrogare. Può essere {@code null}. * @return Oggetto. * @see it.scoppelletti.programmerpower.security.spi.AlgorithmParameterSpecFactory * @see <A HREF="{@docRoot}/it/scoppelletti/programmerpower/security/CryptoUtils.html#idAlg">Algoritmi * di crittografia</A> */ public static KeyGenerator getKeyGenerator(Properties props, String prefix) { int keySize; String alg, name; KeyGenerator gen; AlgorithmParameterSpec params; SecurityResources res = new SecurityResources(); if (props == null) { throw new ArgumentNullException("props"); } name = Strings.concat(prefix, CryptoUtils.PROP_KEYALGORITHM); alg = props.getProperty(name); if (Strings.isNullOrEmpty(alg)) { throw new ArgumentNullException(name); } params = CryptoUtils.getAlgorithmParameterSpec(props, prefix); keySize = CryptoUtils.getKeySize(props, prefix); if (params != null && keySize >= 0) { throw new IllegalArgumentException( res.getArgumentIncompatibilityException(Strings.concat(prefix, CryptoUtils.PROP_PARAMFACTORY), Strings.concat(prefix, CryptoUtils.PROP_KEYSIZE))); } try { gen = KeyGenerator.getInstance(alg); if (params != null) { gen.init(params); } if (keySize >= 0) { gen.init(keySize); } } catch (GeneralSecurityException ex) { throw SecurityUtils.toSecurityException(ex); } return gen; }
From source file:org.structr.util.StructrLicenseManager.java
private boolean checkVolumeLicense(final Map<String, String> properties, final String serversString) { try {//from w w w .j ava 2 s. c om final KeyGenerator kgen = KeyGenerator.getInstance("AES"); final byte[] data = write(properties).getBytes("utf-8"); final String name = properties.get(NameKey); final byte[] expected = name.getBytes("utf-8"); kgen.init(128); for (final String part : serversString.split("[, ]+")) { final String address = part.trim(); if (StringUtils.isNotBlank(address)) { try { logger.info("Trying to verify volume license with server {}", address); final long t0 = System.currentTimeMillis(); final SecretKey aesKey = kgen.generateKey(); // symmetric stream key final byte[] ivspec = RandomUtils.nextBytes(16); // initialization vector for stream cipher final byte[] key = encryptSessionKey(aesKey.getEncoded()); final byte[] encryptedIV = encryptSessionKey(ivspec); final byte[] encryptedData = encryptData(data, aesKey, ivspec); final byte[] response = sendAndReceive(address, key, encryptedIV, encryptedData); final boolean result = verify(expected, response); if (result == true) { logger.info("License verified in {} ms", System.currentTimeMillis() - t0); } return result; } catch (Throwable t) { logger.warn("Unable to verify volume license: {}", t.getMessage()); } } } } catch (Throwable t) { t.printStackTrace(); } return false; }