List of usage examples for javax.crypto KeyGenerator getInstance
public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.openTwoFactor.clientExt.edu.internet2.middleware.morphString.Crypto.java
/** * Generate a key./*from ww w .j av a 2 s.co m*/ * @param cipherName the name of the cipher, if null will default to "AES" * @param keybits the number of bits in the key, if null will default to 128 * @return the bytes comprising the key */ public static byte[] generateKeyBytes(String cipherName, Integer keybits) { KeyGenerator keyGenerator = null; cipherName = cipherName == null ? "AES" : cipherName; try { keyGenerator = KeyGenerator.getInstance(cipherName); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to create KeyGenerator for cipherName=" + cipherName, e); } keyGenerator.init(keybits == null ? 128 : keybits); // 192 and 256 bits may not be available // Generate the secret key specs. SecretKey secretKey = keyGenerator.generateKey(); byte[] keyBytes = secretKey.getEncoded(); return keyBytes; }
From source file:sec_algo.commonenc.java
/** * Creates a new AES key//from w w w.jav a 2 s . c o m */ public void makeKey() { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(AES_Key_Size); SecretKey aeskey = kgen.generateKey(); key = aeskey.getEncoded(); secretkey = new SecretKeySpec(key, "AES"); } catch (Exception e) { e.printStackTrace(); } }
From source file:es.jamisoft.comun.utils.cipher.Cifrado3DES.java
private SecretKey generaDesKey() { try {/* w w w . jav a 2s .c o m*/ KeyGenerator keygen = KeyGenerator.getInstance("DESede"); return keygen.generateKey(); } catch (Exception e) { System.out.println("Error descifrando un texto:" + e); e.printStackTrace(); return null; } }
From source file:servlets.SecretKeyProvider.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . ja v a 2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String opcion = request.getParameter("opcion"); switch (opcion) { case "public": InputStream is = getServletContext().getResourceAsStream("/WEB-INF/server1024.publica"); IOUtils.copy(is, response.getOutputStream()); break; case "secret": { try { SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); request.getSession().setAttribute("clave", secretKey); Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC byte[] bufferPriv = new byte[5000]; InputStream in = getServletContext().getResourceAsStream("/WEB-INF/server1024.privada"); int chars = in.read(bufferPriv, 0, 5000); in.close(); byte[] bufferPriv2 = new byte[chars]; System.arraycopy(bufferPriv, 0, bufferPriv2, 0, chars); // 2.2 Recuperar clave privada desde datos codificados en formato PKCS8 PKCS8EncodedKeySpec clavePrivadaSpec = new PKCS8EncodedKeySpec(bufferPriv2); PrivateKey clavePrivada2 = keyFactoryRSA.generatePrivate(clavePrivadaSpec); // PASO 3a: Poner cifrador en modo CIFRADO cifrador.init(Cipher.ENCRYPT_MODE, clavePrivada2); // Cifra con la clave publica byte[] bufferCifrado = cifrador.doFinal(secretKey.getEncoded()); String mandar = new String(Base64.encodeBase64(bufferCifrado)); response.getWriter().print(mandar); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchProviderException ex) { Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalBlockSizeException ex) { Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex); } catch (BadPaddingException ex) { Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java
/** * Encrypt a value and generate a keyfile. if the keyfile is not found then a new one is created * //from ww w . java 2 s . com * @param value * - value to be encrypted * @throws GeneralSecurityException * - security exception * @return Encrypted value */ @Override public String encrypt(String value) throws GeneralSecurityException { if (!keyFile.exists()) { KeyGenerator keyGen = KeyGenerator.getInstance(AES); keyGen.init(KEY_SIZE); SecretKey sk = keyGen.generateKey(); FileWriter fw = null; try { fw = new FileWriter(keyFile); fw.write(byteArrayToHexString(sk.getEncoded())); fw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } SecretKeySpec sks = getSecretKeySpec(); Cipher cipher = Cipher.getInstance(AES); cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); byte[] encrypted = cipher.doFinal(value.getBytes()); return byteArrayToHexString(encrypted); }
From source file:Main.java
/** * Generate a symmetric DES3 key.//from www. j a va2s . c o m * * @return A DES3 key */ public static SecretKey generateSymmetricKey() throws NoSuchAlgorithmException { KeyGenerator symmetricKeyGenerator = KeyGenerator.getInstance(symmetricAlgorithm); return symmetricKeyGenerator.generateKey(); }
From source file:de.hybris.platform.b2b.punchout.services.impl.SymmetricManager.java
public static String getKey() { String key = null;//ww w .java 2s . c o m try { final KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM); kgen.init(KEY_SIZE); // Generate the secret key specs. final SecretKey skey = kgen.generateKey(); final byte[] raw = skey.getEncoded(); key = new Base64().encodeAsString(raw); } catch (final NoSuchAlgorithmException e) { // should never happen LOG.error("System was unable to generate the key.", e); } return key; }
From source file:com.evolveum.midpoint.init.ConfigurableProtectorFactory.java
public void init() { Configuration config = configuration.getConfiguration(PROTECTOR_CONFIGURATION); protectorConfig = new ProtectorConfiguration(config); //Extract file if not exists if (config.getString("midpoint.home") == null) { return;// w w w. j av a 2s. c o m } File ks = new File(protectorConfig.getKeyStorePath()); if (ks.exists()) { return; } //todo improve FileOutputStream fos = null; try { KeyStore keystore = KeyStore.getInstance("jceks"); char[] password = "changeit".toCharArray(); keystore.load(null, password); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); keystore.setKeyEntry("default", secretKey, "midpoint".toCharArray(), null); fos = new FileOutputStream(protectorConfig.getKeyStorePath()); keystore.store(fos, password); fos.close(); } catch (Exception ex) { throw new SystemException("Couldn't generate keystore, reason: " + ex.getMessage(), ex); } finally { IOUtils.closeQuietly(fos); } }
From source file:br.com.manish.ahy.kernel.util.HashUtil.java
private static Cipher getCipher(boolean enc) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128);// w ww .j a va 2s . co m SecretKeySpec skeySpec = new SecretKeySpec(getBytes(HEXES2), "AES"); Cipher cipher = Cipher.getInstance("AES"); if (enc) { cipher.init(Cipher.ENCRYPT_MODE, skeySpec); } else { cipher.init(Cipher.DECRYPT_MODE, skeySpec); } return cipher; }
From source file:test.unit.org.owasp.webscarab.plugin.saml.SamlTest.java
@Test public void testEncryptionAES() throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128);//from w w w . ja v a 2s. co m SecretKey secretKey = keygen.generateKey(); LOG.debug("secret key algo: " + secretKey.getAlgorithm()); LOG.debug("secret key format: " + secretKey.getFormat()); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); LOG.debug("cipher provider: " + cipher.getProvider().getName()); byte[] result = cipher.doFinal("hello world".getBytes()); assertNotNull(result); byte[] encodedSecretKey = secretKey.getEncoded(); LOG.debug("encoded secret key size: " + encodedSecretKey.length * 8); // decrypt cipher = Cipher.getInstance("AES"); SecretKeySpec secretKeySpec = new SecretKeySpec(encodedSecretKey, "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decryptedResult = cipher.doFinal(result); assertEquals("hello world", new String(decryptedResult)); }