Example usage for javax.crypto KeyGenerator generateKey

List of usage examples for javax.crypto KeyGenerator generateKey

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator generateKey.

Prototype

public final SecretKey generateKey() 

Source Link

Document

Generates a secret key.

Usage

From source file:org.xwiki.contrib.encryption.internal.DefaultEncryptionTool.java

private SecretKeySpec generateRandomKey() {
    try {/*  w w  w . j a v a  2  s .c o  m*/
        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;
    }
}

From source file:com.cfs.util.AESCriptografia.java

public String gerarChaveRandomica() {
    String chave = null;/*from w ww  .j ava 2s  .c  o 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.TestWSSecurityNew14.java

/**
 * Setup method/*from   ww w. j  a  v a 2s. c o m*/
 * <p/>
 * 
 * @throws java.lang.Exception Thrown when there is a problem in setup
 */
protected void setUp() throws Exception {
    AxisClient tmpEngine = new AxisClient(new NullProvider());
    msgContext = new MessageContext(tmpEngine);
    unsignedEnvelope = getSOAPEnvelope();

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    key = keyGen.generateKey();
    keyData = key.getEncoded();
}

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();//ww w. j a  va2  s .  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:com.microsoft.azure.storage.queue.QueueEncryptionPolicy.java

/**
 * Return an encrypted base64 encoded message along with encryption related metadata given a plain text message.
 * /*  w  w  w  .  j  a v a2  s.  c om*/
 * @param inputMessage
 *            The input message in bytes.
 * @return The encrypted message that will be uploaded to the service.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
String encryptMessage(byte[] inputMessage) throws StorageException {
    Utility.assertNotNull("inputMessage", inputMessage);

    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    CloudQueueEncryptedMessage encryptedMessage = new CloudQueueEncryptedMessage();
    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // 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()));

        encryptedMessage.setEncryptedMessageContents(
                new String(Base64.encode(myAes.doFinal(inputMessage, 0, inputMessage.length))));

        encryptionData.setContentEncryptionIV(myAes.getIV());
        encryptedMessage.setEncryptionData(encryptionData);
        return encryptedMessage.serialize();
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:org.apache.ws.security.message.SignatureAlgorithmSuiteTest.java

@org.junit.Test
public void testSymmetricKey() throws Exception {

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);//ww w .j a  va 2 s. co  m
    SecretKey key = keyGen.generateKey();
    byte[] keyData = key.getEncoded();

    WSSecSignature builder = new WSSecSignature();
    builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
    builder.setSecretKey(keyData);
    builder.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document signedDoc = builder.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = XMLUtils.PrettyDocumentToString(signedDoc);
        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(signedDoc, null);
    AlgorithmSuite algorithmSuite = createAlgorithmSuite();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    RequestData data = new RequestData();
    data.setSigCrypto(crypto);
    data.setCallbackHandler(secretKeyCallbackHandler);
    data.setAlgorithmSuite(algorithmSuite);

    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as HMAC-SHA1 is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }

    algorithmSuite.addSignatureMethod(WSConstants.HMAC_SHA1);
    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.floragunn.searchguard.service.SearchGuardService.java

@Inject
public SearchGuardService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.SEARCHGUARD_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    try {/*www  .j  a  va 2  s.co m*/
        method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
        method.setAccessible(true);
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    try {
        searchServiceSetCallbackMethod = SearchService.class.getDeclaredMethod("setCallback",
                SearchContextCallback.class);
        searchServiceSetCallbackMethod.invoke(searchService,
                new ConfigurableSearchContextCallback(settings, auditListener));
    } catch (final Exception e) {
        log.error(e.toString(), e);
        //throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final String keyPath = settings.get(ConfigConstants.SEARCHGUARD_KEY_PATH, ".");
    SecretKey sc = null;
    try {

        final File keyFile = new File(keyPath, "searchguard_node_key.key");

        if (keyFile.exists()) {
            log.debug("Loaded key from {}", keyFile.getAbsolutePath());
            sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
        } else {

            final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
            final KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(128, secRandom);
            final SecretKey secretKey = kg.generateKey();
            final byte[] enckey = secretKey.getEncoded();

            if (enckey == null || enckey.length != 16) {
                throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
            }
            FileUtils.writeByteArrayToFile(keyFile, enckey);
            sc = secretKey;
            log.info("New key written to {}, make sure all nodes have this key", keyFile.getAbsolutePath());
        }

    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/

    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    SearchGuardService.secretKey = sc;
}

From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2Test.java

@Test
public void testGetAlgorithm() throws Exception {

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);// www  . j  av  a  2s . c  om
    SecretKey key = kgen.generateKey();
    LOG.debug("Algorithm AES-128: " + key.getAlgorithm());

}

From source file:com.petalmd.armor.service.ArmorService.java

@Inject
public ArmorService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.ARMOR_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//from   w  ww . j  av  a 2  s .  com

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws Exception {
                method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
                method.setAccessible(true);

                return true;
            }
        });
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    final String keyPath = settings.get(ConfigConstants.ARMOR_KEY_PATH, ".");
    //        AccessController.checkPermission(new FilePermission(keyPath+File.separator+"armor_node_key.key", "write"));
    SecretKey sc = null;
    try {
        sc = AccessController.doPrivileged(new PrivilegedExceptionAction<SecretKey>() {
            @Override
            public SecretKey run() throws Exception {
                final File keyFile = new File(keyPath, "armor_node_key.key");
                SecretKey sc = null;
                if (keyFile.exists()) {
                    log.debug("Loaded key from {}", keyFile.getAbsolutePath());
                    sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
                } else {
                    final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
                    final KeyGenerator kg = KeyGenerator.getInstance("AES");
                    kg.init(128, secRandom);
                    final SecretKey secretKey = kg.generateKey();
                    final byte[] enckey = secretKey.getEncoded();

                    if (enckey == null || enckey.length != 16) {
                        throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
                    }
                    FileUtils.writeByteArrayToFile(keyFile, enckey);
                    sc = secretKey;
                    log.info("New key written to {}, make sure all nodes have this key",
                            keyFile.getAbsolutePath());
                }
                return sc;
            }
        });
    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.ARMOR_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/
    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    ArmorService.secretKey = sc;
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

private SecretKey generateAESKey() throws NoSuchAlgorithmException {
    KeyGenerator aeskeygen = KeyGenerator.getInstance("AES");
    SecretKey aeskey = aeskeygen.generateKey();
    return aeskey;
}