Example usage for java.security Key getEncoded

List of usage examples for java.security Key getEncoded

Introduction

In this page you can find the example usage for java.security Key getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:org.ejbca.ui.cli.CMPKeyUpdateStressTest.java

@Override
protected void execute(String[] args) {
    final String hostName;
    final String keystoreFile;
    final String keystorePassword;
    final String certNameInKeystore;
    final int numberOfThreads;
    final int waitTime;
    final int port;
    final String urlPath;
    final String resultFilePrefix;
    if (args.length < 5) {
        System.out.println(args[0]
                + " <host name> <keystore (p12)> <keystore password> <friendlyname in keystore> [<number of threads>] [<wait time (ms) between each thread is started>] [<port>] [<URL path of servlet. use 'null' to get EJBCA (not proxy) default>] [<certificate file prefix. set this if you want all received certificates stored on files>]");
        System.out.println(/*from   ww w  . j  a  va2 s .  c  o m*/
                "EJBCA build configuration requirements: cmp.operationmode=normal, cmp.allowraverifypopo=true, cmp.allowautomatickeyupdate=true, cmp.allowupdatewithsamekey=true");
        //            System.out.println("EJBCA build configuration optional: cmp.ra.certificateprofile=KeyId cmp.ra.endentityprofile=KeyId (used when the KeyId argument should be used as profile name).");
        System.out.println(
                "Ejbca expects the following: There exists an end entity with a generated certificate. The end entity's certificate and its private key are stored in the keystore used "
                        + "in the commandline. The end entity's certificate's 'friendly name' in the keystore is the one used in the command line. Such keystore can be obtained, for example, by specifying "
                        + "the token to be 'P12' when creating the end entity and then download the keystore by choosing 'create keystore' from the public web");
        return;
    }
    hostName = args[1];
    keystoreFile = args[2];
    keystorePassword = args[3];
    certNameInKeystore = args[4];
    numberOfThreads = args.length > 5 ? Integer.parseInt(args[5].trim()) : 1;
    waitTime = args.length > 6 ? Integer.parseInt(args[6].trim()) : 0;
    port = args.length > 7 ? Integer.parseInt(args[7].trim()) : 8080;
    //        isHttp = true;
    urlPath = args.length > 8 && args[8].toLowerCase().indexOf("null") < 0 ? args[8].trim() : null;
    resultFilePrefix = args.length > 9 ? args[9].trim() : null;

    CryptoProviderTools.installBCProviderIfNotAvailable();

    Certificate cacert = null;
    Certificate extracert = null;
    PrivateKey oldCertKey = null;

    FileInputStream file_inputstream;
    try {
        file_inputstream = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, keystorePassword.toCharArray());
        Key key = keyStore.getKey(certNameInKeystore, keystorePassword.toCharArray());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        oldCertKey = keyFactory.generatePrivate(keySpec);
        //extracert = keyStore.getCertificate(certNameInKeystore);

        Certificate[] certs = keyStore.getCertificateChain(certNameInKeystore);
        extracert = certs[0];
        cacert = certs[1];

    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
        System.exit(-1);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    try {
        new StressTest(hostName, port, numberOfThreads, waitTime, urlPath, resultFilePrefix, keystorePassword,
                cacert, oldCertKey, extracert);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnectorFactoryConnIdImpl.java

private void selfTestGuardedString(OperationResult parentTestResult) {
    OperationResult result = parentTestResult
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString");

    OperationResult subresult = result//from   ww  w  . j a  v a 2  s  .co m
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.encryptorReflection");
    EncryptorFactory encryptorFactory = EncryptorFactory.getInstance();
    subresult.addReturn("encryptorFactoryImpl", encryptorFactory.getClass());
    LOGGER.debug("Encryptor factory implementation class: {}", encryptorFactory.getClass());
    Encryptor encryptor = EncryptorFactory.getInstance().newRandomEncryptor();
    subresult.addReturn("encryptorImpl", encryptor.getClass());
    LOGGER.debug("Encryptor implementation class: {}", encryptor.getClass());
    if (encryptor.getClass().getName().equals("org.identityconnectors.common.security.impl.EncryptorImpl")) {
        // let's do some reflection magic to have a look inside
        try {
            LOGGER.trace("Encryptor fields: {}", Arrays.asList(encryptor.getClass().getDeclaredFields()));
            Field keyField = encryptor.getClass().getDeclaredField("key");
            keyField.setAccessible(true);
            Key key = (Key) keyField.get(encryptor);
            subresult.addReturn("keyAlgorithm", key.getAlgorithm());
            subresult.addReturn("keyLength", key.getEncoded().length * 8);
            subresult.addReturn("keyFormat", key.getFormat());
            subresult.recordSuccess();
        } catch (IllegalArgumentException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (IllegalAccessException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (NoSuchFieldException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (SecurityException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        }
    }

    OperationResult encryptorSubresult = result
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.encryptor");
    try {
        String plainString = "Scurvy seadog";
        byte[] encryptedBytes = encryptor.encrypt(plainString.getBytes());
        byte[] decryptedBytes = encryptor.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes);
        if (!plainString.equals(decryptedString)) {
            encryptorSubresult.recordFatalError(
                    "Encryptor roundtrip failed; encrypted=" + plainString + ", decrypted=" + decryptedString);
        } else {
            encryptorSubresult.recordSuccess();
        }
    } catch (Throwable e) {
        LOGGER.error("Encryptor operation error: {}", e.getMessage(), e);
        encryptorSubresult.recordFatalError("Encryptor opeation error: " + e.getMessage(), e);
    }

    final OperationResult guardedStringSubresult = result
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.guardedString");
    // try to encrypt and decrypt GuardedString
    try {
        final String origString = "Shiver me timbers";
        // This should encrypt it
        GuardedString guardedString = new GuardedString(origString.toCharArray());
        // and this should decrypt it
        guardedString.access(new GuardedString.Accessor() {
            @Override
            public void access(char[] decryptedChars) {
                if (!(new String(decryptedChars)).equals(origString)) {
                    guardedStringSubresult.recordFatalError("GuardeString roundtrip failed; encrypted="
                            + origString + ", decrypted=" + (new String(decryptedChars)));
                }
            }
        });
        guardedStringSubresult.recordSuccessIfUnknown();
    } catch (Throwable e) {
        LOGGER.error("GuardedString operation error: {}", e.getMessage(), e);
        guardedStringSubresult.recordFatalError("GuardedString opeation error: " + e.getMessage(), e);
    }

    result.computeStatus();
}

From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java

/**
 * @throws SystemException if jceks keystore is not available on {@link ProtectorImpl#getKeyStorePath}
 *//*from  w  ww  .j  av  a2s .com*/
public void init() {
    InputStream stream = null;
    try {
        // Test if use file or classpath resource
        File f = new File(getKeyStorePath());
        if (f.exists()) {
            LOGGER.info("Using file keystore at {}", getKeyStorePath());
            if (!f.canRead()) {
                LOGGER.error("Provided keystore file {} is unreadable.", getKeyStorePath());
                throw new EncryptionException(
                        "Provided keystore file " + getKeyStorePath() + " is unreadable.");
            }
            stream = new FileInputStream(f);

            // Use class path keystore
        } else {
            LOGGER.warn("Using default keystore from classpath ({}).", getKeyStorePath());
            // Read from class path

            stream = ProtectorImpl.class.getClassLoader().getResourceAsStream(getKeyStorePath());
            // ugly dirty hack to have second chance to find keystore on
            // class path
            if (stream == null) {
                stream = ProtectorImpl.class.getClassLoader()
                        .getResourceAsStream("com/../../" + getKeyStorePath());
            }
        }
        // Test if we have valid stream
        if (stream == null) {
            throw new EncryptionException("Couldn't load keystore as resource '" + getKeyStorePath() + "'");
        }
        // Load keystore
        keyStore.load(stream, getKeyStorePassword().toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        Set<String> keyEntryAliasesInKeyStore = new HashSet<>();

        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance(KEY_DIGEST_TYPE);
        } catch (NoSuchAlgorithmException ex) {
            throw new EncryptionException(ex.getMessage(), ex);
        }

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            try {
                if (!keyStore.isKeyEntry(alias)) {
                    LOGGER.trace("Alias {} is not a key entry and shall be skipped", alias);
                    continue;
                }
                keyEntryAliasesInKeyStore.add(alias);
                Key key = keyStore.getKey(alias, KEY_PASSWORD);
                if (!(key instanceof SecretKey)) {
                    continue;
                }
                final SecretKey secretKey = (SecretKey) key;
                LOGGER.trace("Found secret key for alias {}", alias);
                aliasToSecretKeyHashMap.put(alias, secretKey);

                final String digest = Base64.encode(sha1.digest(key.getEncoded()));
                LOGGER.trace("Calculated digest {} for key alias {}", digest, key);
                digestToSecretKeyHashMap.put(digest, secretKey);

            } catch (UnrecoverableKeyException ex) {
                LOGGER.trace("Couldn't recover key {} from keystore, reason: {}",
                        new Object[] { alias, ex.getMessage() });
            }
        }
        LOGGER.trace("Found {} aliases in keystore identified as secret keys", aliasToSecretKeyHashMap.size());
        stream.close();

        // Initialize trust manager list

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStore);
        trustManagers = new ArrayList<>();
        for (TrustManager trustManager : tmFactory.getTrustManagers()) {
            trustManagers.add(trustManager);
        }

        //init apache crypto library
        Init.init();

    } catch (Exception ex) {
        LOGGER.error("Unable to work with keystore {}, reason {}.",
                new Object[] { getKeyStorePath(), ex.getMessage() }, ex);
        throw new SystemException(ex.getMessage(), ex);
    }

    randomNumberGenerator = new SecureRandom();
}

From source file:org.apache.xml.security.stax.impl.processor.input.AbstractDecryptInputProcessor.java

private XMLSecEvent processEvent(InputProcessorChain inputProcessorChain, boolean isSecurityHeaderEvent)
        throws XMLStreamException, XMLSecurityException {

    if (!tmpXmlEventList.isEmpty()) {
        return tmpXmlEventList.pollLast();
    }/*w w w .ja va 2 s .co m*/

    XMLSecEvent xmlSecEvent = isSecurityHeaderEvent ? inputProcessorChain.processHeaderEvent()
            : inputProcessorChain.processEvent();

    boolean encryptedHeader = false;

    if (xmlSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT) {
        XMLSecStartElement xmlSecStartElement = xmlSecEvent.asStartElement();

        //buffer the events until the EncryptedData Element appears and discard it if we found the reference inside it
        //otherwise replay it
        if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_wsse11_EncryptedHeader)) {
            xmlSecEvent = readAndBufferEncryptedHeader(inputProcessorChain, isSecurityHeaderEvent, xmlSecEvent);
            xmlSecStartElement = xmlSecEvent.asStartElement();
            encryptedHeader = true;
        }

        //check if the current start-element has the name EncryptedData and an Id attribute
        if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
            ReferenceType referenceType = null;
            if (references != null) {
                referenceType = matchesReferenceId(xmlSecStartElement);
                if (referenceType == null) {
                    //if the events were not for us (no matching reference-id the we have to replay the EncryptedHeader elements)
                    if (!tmpXmlEventList.isEmpty()) {
                        return tmpXmlEventList.pollLast();
                    }
                    return xmlSecEvent;
                }
                //duplicate id's are forbidden
                if (processedReferences.contains(referenceType)) {
                    throw new XMLSecurityException("signature.Verification.MultipleIDs");
                }

                processedReferences.add(referenceType);
            }
            tmpXmlEventList.clear();

            //the following logic reads the encryptedData structure and doesn't pass them further
            //through the chain
            InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this);

            EncryptedDataType encryptedDataType = parseEncryptedDataStructure(isSecurityHeaderEvent,
                    xmlSecEvent, subInputProcessorChain);
            if (encryptedDataType.getId() == null) {
                encryptedDataType.setId(IDGenerator.generateID(null));
            }

            InboundSecurityToken inboundSecurityToken = getSecurityToken(inputProcessorChain,
                    xmlSecStartElement, encryptedDataType);
            handleSecurityToken(inboundSecurityToken, inputProcessorChain.getSecurityContext(),
                    encryptedDataType);

            final String algorithmURI = encryptedDataType.getEncryptionMethod().getAlgorithm();
            final int ivLength = JCEAlgorithmMapper.getIVLengthFromURI(algorithmURI) / 8;
            Cipher symCipher = getCipher(algorithmURI);

            if (encryptedDataType.getCipherData().getCipherReference() != null) {
                handleCipherReference(inputProcessorChain, encryptedDataType, symCipher, inboundSecurityToken);
                subInputProcessorChain.reset();
                return isSecurityHeaderEvent ? subInputProcessorChain.processHeaderEvent()
                        : subInputProcessorChain.processEvent();
            }

            //create a new Thread for streaming decryption
            DecryptionThread decryptionThread = new DecryptionThread(subInputProcessorChain,
                    isSecurityHeaderEvent);
            Key decryptionKey = inboundSecurityToken.getSecretKey(algorithmURI, XMLSecurityConstants.Enc,
                    encryptedDataType.getId());
            decryptionKey = XMLSecurityUtils.prepareSecretKey(algorithmURI, decryptionKey.getEncoded());
            decryptionThread.setSecretKey(decryptionKey);
            decryptionThread.setSymmetricCipher(symCipher);
            decryptionThread.setIvLength(ivLength);
            XMLSecStartElement parentXMLSecStartElement = xmlSecStartElement.getParentXMLSecStartElement();
            if (encryptedHeader) {
                parentXMLSecStartElement = parentXMLSecStartElement.getParentXMLSecStartElement();
            }
            AbstractDecryptedEventReaderInputProcessor decryptedEventReaderInputProcessor = newDecryptedEventReaderInputProcessor(
                    encryptedHeader, parentXMLSecStartElement, encryptedDataType, inboundSecurityToken,
                    inputProcessorChain.getSecurityContext());

            //add the new created EventReader processor to the chain.
            inputProcessorChain.addProcessor(decryptedEventReaderInputProcessor);

            inputProcessorChain.getDocumentContext().setIsInEncryptedContent(
                    inputProcessorChain.getProcessors().indexOf(decryptedEventReaderInputProcessor),
                    decryptedEventReaderInputProcessor);

            //fire here only ContentEncryptedElementEvents
            //the other ones will be fired later, because we don't know the encrypted element name yet
            //important: this must occur after setIsInEncryptedContent!
            if (SecurePart.Modifier.Content.getModifier().equals(encryptedDataType.getType())) {
                handleEncryptedContent(inputProcessorChain, xmlSecStartElement.getParentXMLSecStartElement(),
                        inboundSecurityToken, encryptedDataType);
            }

            Thread thread = new Thread(decryptionThread);
            thread.setPriority(Thread.NORM_PRIORITY + 1);
            thread.setName("decryption thread");
            //when an exception in the decryption thread occurs, we want to forward them:
            thread.setUncaughtExceptionHandler(decryptedEventReaderInputProcessor);

            decryptedEventReaderInputProcessor.setDecryptionThread(thread);

            //we have to start the thread before we call decryptionThread.getPipedInputStream().
            //Otherwise we will end in a deadlock, because the StAX reader expects already data.
            //@See some lines below:
            log.debug("Starting decryption thread");
            thread.start();

            InputStream prologInputStream;
            InputStream epilogInputStream;
            try {
                prologInputStream = writeWrapperStartElement(xmlSecStartElement);
                epilogInputStream = writeWrapperEndElement();
            } catch (UnsupportedEncodingException e) {
                throw new XMLSecurityException(e);
            } catch (IOException e) {
                throw new XMLSecurityException(e);
            }

            InputStream decryptInputStream = decryptionThread.getPipedInputStream();
            decryptInputStream = applyTransforms(referenceType, decryptInputStream);

            //spec says (4.2): "The cleartext octet sequence obtained in step 3 is
            //interpreted as UTF-8 encoded character data."
            XMLStreamReader xmlStreamReader = inputProcessorChain.getSecurityContext()
                    .<XMLInputFactory>get(XMLSecurityConstants.XMLINPUTFACTORY).createXMLStreamReader(
                            new MultiInputStream(prologInputStream, decryptInputStream, epilogInputStream),
                            "UTF-8");

            //forward to wrapper element
            forwardToWrapperElement(xmlStreamReader);

            decryptedEventReaderInputProcessor.setXmlStreamReader(xmlStreamReader);

            if (isSecurityHeaderEvent) {
                return decryptedEventReaderInputProcessor.processNextHeaderEvent(inputProcessorChain);
            } else {
                return decryptedEventReaderInputProcessor.processNextEvent(inputProcessorChain);
            }
        }
    }
    return xmlSecEvent;
}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java

@Override
public String getEncryptedLicense(PublicKey targetKey) throws SystemStateException, OperationException {
    byte[] licenseAsBytes;
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(bos)) {
        out.writeObject(this);
        licenseAsBytes = bos.toByteArray();
    } catch (IOException ex) {
        throw new OperationException("An error occured while serializing the license", ex);
    }//from   w  w w . j  a  v a 2  s  .c  om
    SecureRandom random = new SecureRandom();
    Cipher aescipher;
    Cipher rsacipher;

    KeyGenerator aesgenerator;
    Key symkey;
    try {
        aesgenerator = KeyGenerator.getInstance(symmetricKeyType, provider);
        aesgenerator.init(128, random);
        symkey = aesgenerator.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SystemStateException("The specified symkey could not be generated.", ex);
    }

    try {
        aescipher = Cipher.getInstance(symmetricEncoding, provider);
        rsacipher = Cipher.getInstance(asymmetricEncoding, provider);

        aescipher.init(Cipher.ENCRYPT_MODE, symkey);
        rsacipher.init(Cipher.ENCRYPT_MODE, targetKey);
    } catch (NoSuchAlgorithmException | NoSuchProviderException
            | /*InvalidKeySpecException |*/ NoSuchPaddingException | InvalidKeyException ex) {
        throw new SystemStateException("The specified encryption provider or algorithm was not found", ex);
    }

    String encryptedLicense;
    try {
        byte[] encryptedsymkey = rsacipher.doFinal(symkey.getEncoded());

        byte[] encryptedlicense = aescipher.doFinal(licenseAsBytes);
        byte[] licenseWithKey = new byte[encryptedsymkey.length + encryptedlicense.length];
        System.arraycopy(encryptedsymkey, 0, licenseWithKey, 0, encryptedsymkey.length);
        System.arraycopy(encryptedlicense, 0, licenseWithKey, encryptedsymkey.length, encryptedlicense.length);
        encryptedLicense = Base64.encodeBase64String(licenseWithKey);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        throw new OperationException("Could not encode to base64", ex);
    }
    return encryptedLicense;

}

From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java

@SuppressWarnings("resource")
public void run() {

    SingletonForSSFMP info = null;/*from  w w  w. j  av  a2 s .  co m*/
    SingletonForSSFMP2 info2 = null;
    SingletonForSSFMP3 info3 = null;

    switch (abs) {
    case 0:
        info = SingletonForSSFMP.getInstance();
        break;
    case 1:
        info2 = SingletonForSSFMP2.getInstance();
        break;
    case 2:
        info3 = SingletonForSSFMP3.getInstance();
        break;
    default:
        //info = SingletonForMyStreamer.getInstance();
        break;
    }

    int seqTsEnc = 0; //info.getSeqTsEnc();
    if (!modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsEnc();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsEnc();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsEnc();
        }
    } else if (modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsCapturedTimeShifted();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsCapturedTimeShifted();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsCapturedTimeShifted();
        }
    }

    if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
        seqTsEnc = info.getSeqTsLast();
    } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
        seqTsEnc = info2.getSeqTsLast();
    } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
        seqTsEnc = info3.getSeqTsLast();
    }

    log.debug(MARKER_Encrypter, "{} Begin : Encryption of seqTsEnc : {}",
            Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

    Key sKey;
    Cipher c;
    FileOutputStream keyOut;
    FileWriter ivOut;
    FileInputStream fis;
    BufferedInputStream bis;
    FileOutputStream fos;
    CipherOutputStream cos;

    try {

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        sKey = makeKey(128); // Key length is 128bit
        c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        //         log.debug(MARKER_Encrypter, "{} [c.getAlgorithm()] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), c.getAlgorithm());
        c.init(Cipher.ENCRYPT_MODE, sKey);

        // Set Key File Name at random
        String keyPre = RandomStringUtils.randomAlphabetic(10);
        keyOut = new FileOutputStream(streamPath + FILE_SEPARATOR + keyPre + seqTsEnc + ".key");

        if ((abs == 0) && (info != null)) {
            info.addKeyArrayList(keyPre);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addKeyArrayList(keyPre);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addKeyArrayList(keyPre);
        }

        byte[] keyOutByte = sKey.getEncoded();
        keyOut.write(keyOutByte);
        keyOut.close();

        byte[] iv = c.getIV();
        //         log.debug(MARKER_Encrypter, "{} [iv.length] {} [byte]", Thread.currentThread().getStackTrace()[1].getMethodName(), iv.length);

        String ivHex = "";
        for (int i = 0; i < iv.length; i++) {
            String ivHexTmp = String.format("%02x", iv[i]).toUpperCase();
            ivHex = ivHex + ivHexTmp;
        }

        String ivPre = RandomStringUtils.randomAlphabetic(10);
        ivOut = new FileWriter(streamPath + FILE_SEPARATOR + ivPre + seqTsEnc + ".iv");
        ivOut.write(ivHex);
        ivOut.close();

        //         log.debug(MARKER_Encrypter, "{} [iv] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), ivHex);

        if ((abs == 0) && (info != null)) {
            info.addIvArrayList(ivHex);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addIvArrayList(ivHex);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addIvArrayList(ivHex);
        }

        fis = new FileInputStream(TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequence" + seqTsEnc + ".ts");
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
        cos = new CipherOutputStream(fos, c);
        if (modeLive.equals("capturedTimeShifted")) {
            fis = new FileInputStream(
                    TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequenceEncoded" + seqTsEnc + ".ts");
            bis = new BufferedInputStream(fis);
            fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
            cos = new CipherOutputStream(fos, c);
        }

        byte[] buf = new byte[TS_PACKET_LENGTH];

        int ch;
        while ((ch = bis.read(buf)) != -1) {
            cos.write(buf, 0, ch);
        }
        cos.close();
        fos.close();
        bis.close();
        fis.close();

        log.debug(MARKER_Encrypter, "{} End : Encryption of seqTsEnc : {}",
                Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

        if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        }

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } // try
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
    if (log.isInfoEnabled()) {
        log.info("Loaded cluster key store from: {}", ksLocation);
        try {/*from   w ww .j  a va  2s . c o m*/
            for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
                String alias = e.nextElement();
                Key key = ks.getKey(alias, ksPwd);
                Certificate[] certs = ks.getCertificateChain(alias);
                log.debug("{} -> {}", alias, certs);
                final byte[] encodedKey;
                if (certs != null && certs.length > 0) {
                    encodedKey = certs[0].getEncoded();
                } else {
                    log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
                    encodedKey = key.getEncoded();
                }
                // Compute the certificate's fingerprint (use the key if certificate cannot be found)
                MessageDigest digest = MessageDigest.getInstance("SHA1");
                digest.update(encodedKey);
                StringJoiner fingerprint = new StringJoiner(":");
                for (byte b : digest.digest()) {
                    fingerprint.add(String.format("%02X", b));
                }
                log.info("{} -> {}", alias, fingerprint);
            }
        } catch (Exception e) {
            log.warn("Unable to print contents of key store: {}", ksLocation, e);
        }
    }
}