List of usage examples for javax.crypto KeyGenerator init
public final void init(int keysize)
From source file:org.wso2.carbon.apimgt.core.impl.FileEncryptionUtility.java
/** * Creates and stores an AES key/*from w ww .j a va 2s .c o m*/ * * @throws APIManagementException if an error occurs while creating or storing AES key */ void createAndStoreAESKey() throws APIManagementException { try { //create a new AES key KeyGenerator keyGenerator = KeyGenerator.getInstance(EncryptionConstants.AES); keyGenerator.init(AES_Key_Size); byte[] aesKey = keyGenerator.generateKey().getEncoded(); //store key => encrypt -> encode -> chars -> string byte[] encryptedKeyBytes = SecureVaultUtils.base64Encode(getSecureVault().encrypt(aesKey)); String encryptedKeyString = new String(SecureVaultUtils.toChars(encryptedKeyBytes)); Files.deleteIfExists(Paths.get(getAesKeyFileLocation())); APIFileUtils.createFile(getAesKeyFileLocation()); APIFileUtils.writeToFile(getAesKeyFileLocation(), encryptedKeyString); log.debug("AES key successfully created and stored"); } catch (NoSuchAlgorithmException | SecureVaultException | APIMgtDAOException | IOException e) { String msg = "Error while creating or storing created AES key"; throw new APIManagementException(msg, e); } }
From source file:com.z299studio.pb.FingerprintDialog.java
private void initCipher(int mode) { try {/*from w w w .ja v a 2 s.c o m*/ IvParameterSpec ivParams; KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey key; mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); if (mode == Cipher.ENCRYPT_MODE) { KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); mCipher.init(mode, keyGenerator.generateKey()); } else { key = (SecretKey) keyStore.getKey(KEY_NAME, null); ivParams = new IvParameterSpec(Application.getInstance().getFpIv()); mCipher.init(mode, key, ivParams); } mCryptoObject = new FingerprintManager.CryptoObject(mCipher); } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidAlgorithmParameterException | NoSuchPaddingException e) { Log.e("Pb:FingerprintDialog", "Runtime error in initCipher."); Log.e("Pb:FingerprintDialog", e.toString()); } }
From source file:sec_algo.commonenc.java
/** * Creates a new AES key//from w ww . ja va 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:org.apache.ws.security.message.EncryptionAlgorithmSuiteTest.java
@org.junit.Test public void testSymmetricEncryption() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); byte[] keyData = key.getEncoded(); WSSecEncrypt builder = new WSSecEncrypt(); builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER); builder.setSymmetricKey(key);//w w w .j ava 2 s . c o m 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:com.cfs.util.AESCriptografia.java
public String gerarChaveRandomica() { String chave = null;// ww w .j ava 2s . co m try { /* Cria o gerador de chaves */ KeyGenerator keygen = KeyGenerator.getInstance("AES"); /* Inicializa o gerador de chaves */ SecureRandom random = new SecureRandom(); keygen.init(random); /* Cria uma chave */ SecretKey key = keygen.generateKey(); /* Captura a chave na forma de bytes */ byte[] buffer = key.getEncoded(); /* Codifica a chave gerada */ byte[] chaveGerada = Base64.encodeBase64(buffer); /* Converte a chave para texto */ chave = new String(chaveGerada, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } /* Retorna a chave */ return chave; }
From source file:wssec.TestWSSecurityNew17.java
/** * Setup method/*from ww w. j ava 2s. co 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(); }
From source file:net.spfbl.core.Server.java
private static SecretKey getPrivateKey() { if (privateKey == null) { try {//from www. j a v a 2s . c o m File file = new File("./data/server.key"); if (file.exists()) { FileInputStream fileInputStream = new FileInputStream(file); try { privateKey = SerializationUtils.deserialize(fileInputStream); } finally { fileInputStream.close(); } } else { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(new SecureRandom()); SecretKey key = keyGen.generateKey(); FileOutputStream outputStream = new FileOutputStream(file); try { SerializationUtils.serialize(key, outputStream); } finally { outputStream.close(); } privateKey = key; } } catch (Exception ex) { Server.logError(ex); } } return privateKey; }
From source file:com.microsoft.azure.storage.blob.BlobEncryptionPolicy.java
/** * Set up the encryption context required for encrypting blobs. * @param metadata//from ww w .j av a2 s. com * Reference to blob metadata object that is used to set the encryption materials. * @param noPadding * Value indicating if the padding mode should be set or not. * @return The Cipher to use to decrypt the blob. * @throws StorageException * An exception representing any error which occurred during the operation. */ Cipher createAndSetEncryptionContext(Map<String, String> metadata, boolean noPadding) throws StorageException { Utility.assertNotNull("metadata", metadata); // The Key should be set on the policy for encryption. Otherwise, throw an error. if (this.keyWrapper == null) { throw new IllegalArgumentException(SR.KEY_MISSING); } try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); Cipher myAes; if (noPadding) { myAes = Cipher.getInstance("AES/CBC/NoPadding"); } else { myAes = Cipher.getInstance("AES/CBC/PKCS5Padding"); } SecretKey aesKey = keyGen.generateKey(); myAes.init(Cipher.ENCRYPT_MODE, aesKey); BlobEncryptionData encryptionData = new BlobEncryptionData(); encryptionData.setEncryptionAgent(new EncryptionAgent( Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1, EncryptionAlgorithm.AES_CBC_256)); // Wrap key Pair<byte[], String> encryptedKey = this.keyWrapper .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get(); encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(), encryptedKey.getKey(), encryptedKey.getValue())); encryptionData.setContentEncryptionIV(myAes.getIV()); metadata.put(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA, encryptionData.serialize()); return myAes; } catch (Exception e) { throw StorageException.translateClientException(e); } }
From source file:com.kk.dic.action.Upload.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); out = response.getWriter();// www . j a v a 2s. c o m Connection con; PreparedStatement pstm = null; String fname = ""; String keyword = ""; String cd = ""; String a = (String) request.getSession().getAttribute("email"); System.out.println("User Name : " + a); try { boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { return; } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); out.print("one"); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); if (fileItem.getFieldName().equals("name")) { fname = fileItem.getString(); System.out.println("File Name" + fname); } else if (fileItem.getFieldName().equals("keyword")) { keyword = fileItem.getString(); System.out.println("File Keyword" + keyword); } else { } boolean isFormField = fileItem.isFormField(); if (isFormField) { } else { out.print("one"); try { con = Dbconnection.getConnection(); pstm = con.prepareStatement( "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)"); out.println("getD " + fileItem.getName()); String str = getStringFromInputStream(fileItem.getInputStream()); // secretkey generating KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); System.out.println("secret key:" + secretKey); //converting secretkey to String byte[] be = secretKey.getEncoded();//encoding secretkey String skey = Base64.encode(be); System.out.println("converted secretkey to string:" + skey); String cipher = new encryption().encrypt(str, secretKey); System.out.println(str); //for get extension from given file String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.')); System.out.println("File Extension" + b); pstm.setBinaryStream(1, fileItem.getInputStream()); pstm.setString(2, keyword); pstm.setString(3, b); pstm.setString(4, fname); pstm.setDate(5, getCurrentDate()); pstm.setString(6, a); pstm.setLong(7, fileItem.getSize()); pstm.setString(8, cipher); pstm.setString(9, "0"); pstm.setString(10, skey); /*Cloud Start*/ File f = new File("D:/" + fileItem.getName()); out.print("<br/>" + f.getName()); FileWriter fw = new FileWriter(f); fw.write(cipher); fw.close(); Ftpcon ftpcon = new Ftpcon(); ftpcon.upload(f, fname); /*Cloud End*/ int i = pstm.executeUpdate(); if (i == 1) { response.sendRedirect("upload.jsp?msg=success"); } else { response.sendRedirect("upload.jsp?msgg=failed"); } con.close(); } catch (Exception e) { out.println(e); } } } } catch (Exception ex) { out.print(ex); Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } } finally { out.close(); } }
From source file:org.xwiki.contrib.encryption.internal.DefaultEncryptionTool.java
private SecretKeySpec generateRandomKey() { try {/* w w w . j a v a2s . c om*/ KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey key = keyGenerator.generateKey(); return (SecretKeySpec) key; } catch (Exception e) { logger.warn("Exception encountered while generating the encryption key : " + e.getMessage()); return null; } }