Example usage for java.util Random nextBytes

List of usage examples for java.util Random nextBytes

Introduction

In this page you can find the example usage for java.util Random nextBytes.

Prototype

public void nextBytes(byte[] bytes) 

Source Link

Document

Generates random bytes and places them into a user-supplied byte array.

Usage

From source file:com.google.uzaygezen.core.BitVectorTest.java

private void checkToBigEndianByteArrayAndCopyFromBigEndianAreInverse(Function<Integer, BitVector> factory) {
    Random random = new Random(TestUtils.SEED);
    for (int sizeUpperLimit = 0; sizeUpperLimit < 128; ++sizeUpperLimit) {
        byte[] array = new byte[sizeUpperLimit];
        random.nextBytes(array);
        BitSet bs = BitSet.valueOf(array);
        ArrayUtils.reverse(array);// w w w .  j  a  v a  2  s  .  com
        int logicalSize = bs.length();
        int n = MathUtils.bitCountToByteCount(logicalSize);
        for (int i = 0; i < array.length - n; ++i) {
            assert array[i] == 0;
        }
        byte[] bigEndian = Arrays.copyOfRange(array, array.length - n, array.length);
        for (int size = logicalSize; size <= n << 3; ++size) {
            BitVector bv = factory.apply(size);
            bv.copyFromBigEndian(bigEndian);
            byte[] actual = bv.toBigEndianByteArray();
            assertArrayEquals(bigEndian, actual);
        }
    }
}

From source file:org.apache.flink.table.codegen.SortCodeGeneratorTest.java

private Object value2(InternalType type, Random rnd) {
    if (type.equals(InternalTypes.BOOLEAN)) {
        return false;
    } else if (type.equals(InternalTypes.BYTE)) {
        return (byte) 0;
    } else if (type.equals(InternalTypes.SHORT)) {
        return (short) 0;
    } else if (type.equals(InternalTypes.INT)) {
        return 0;
    } else if (type.equals(InternalTypes.LONG)) {
        return 0L;
    } else if (type.equals(InternalTypes.FLOAT)) {
        return 0f;
    } else if (type.equals(InternalTypes.DOUBLE)) {
        return 0d;
    } else if (type.equals(InternalTypes.STRING)) {
        return BinaryString.fromString("0");
    } else if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        return Decimal.fromBigDecimal(new BigDecimal(0), decimalType.precision(), decimalType.scale());
    } else if (type instanceof ArrayType || type.equals(InternalTypes.BINARY)) {
        byte[] bytes = new byte[rnd.nextInt(7) + 10];
        rnd.nextBytes(bytes);
        return type.equals(InternalTypes.BINARY) ? bytes : BinaryArray.fromPrimitiveArray(bytes);
    } else if (type instanceof RowType) {
        RowType rowType = (RowType) type;
        if (rowType.getTypeAt(0).equals(InternalTypes.INT)) {
            return GenericRow.of(rnd.nextInt());
        } else {//  www.  jav  a  2s. c  om
            return GenericRow.of(GenericRow.of(new Object[] { null }));
        }
    } else if (type instanceof GenericType) {
        return new BinaryGeneric<>(rnd.nextInt(), IntSerializer.INSTANCE);
    } else {
        throw new RuntimeException("Not support!");
    }
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public Connection(@Nullable Connection oldConnection) {
    String frc = null;//from w  w w  .j a v a 2 s.c o m
    String serial = null;
    String deviceId = null;
    if (oldConnection != null) {
        frc = oldConnection.getFrc();
        serial = oldConnection.getSerial();
        deviceId = oldConnection.getDeviceId();

    }
    Random rand = new Random();
    if (frc != null) {
        this.frc = frc;
    } else {
        // generate frc
        byte[] frcBinary = new byte[313];
        rand.nextBytes(frcBinary);
        this.frc = Base64.getEncoder().encodeToString(frcBinary);
    }
    if (serial != null) {
        this.serial = serial;
    } else {
        // generate serial
        byte[] serialBinary = new byte[16];
        rand.nextBytes(serialBinary);
        this.serial = HexUtils.bytesToHex(serialBinary);
    }
    if (deviceId != null) {
        this.deviceId = deviceId;
    } else {
        // generate device id
        StringBuilder deviceIdBuilder = new StringBuilder();
        for (int i = 0; i < 64; i++) {
            deviceIdBuilder.append(rand.nextInt(9));
        }
        deviceIdBuilder.append("23413249564c5635564d32573831");
        this.deviceId = deviceIdBuilder.toString();
    }

    // build user agent
    this.userAgent = "AmazonWebView/Amazon Alexa/2.2.223830.0/iOS/11.4.1/iPhone";

    // setAmazonSite(amazonSite);

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonWithNullSerialization = gsonBuilder.create();
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestEditLog.java

/**
 * "Fuzz" test for the edit log./*from w  w w . ja v a2 s. c o m*/
 *
 * This tests that we can read random garbage from the edit log without
 * crashing the JVM or throwing an unchecked exception.
 */
@Test
public void testFuzzSequences() throws IOException {
    final int MAX_GARBAGE_LENGTH = 512;
    final int MAX_INVALID_SEQ = 5000;
    // The seed to use for our random number generator.  When given the same
    // seed, Java.util.Random will always produce the same sequence of values.
    // This is important because it means that the test is deterministic and
    // repeatable on any machine.
    final int RANDOM_SEED = 123;

    Random r = new Random(RANDOM_SEED);
    for (int i = 0; i < MAX_INVALID_SEQ; i++) {
        byte[] garbage = new byte[r.nextInt(MAX_GARBAGE_LENGTH)];
        r.nextBytes(garbage);
        validateNoCrash(garbage);
    }
}

From source file:org.apache.flink.table.codegen.SortCodeGeneratorTest.java

private Object value1(InternalType type, Random rnd) {
    if (type.equals(InternalTypes.BOOLEAN)) {
        return false;
    } else if (type.equals(InternalTypes.BYTE)) {
        return Byte.MIN_VALUE;
    } else if (type.equals(InternalTypes.SHORT)) {
        return Short.MIN_VALUE;
    } else if (type.equals(InternalTypes.INT)) {
        return Integer.MIN_VALUE;
    } else if (type.equals(InternalTypes.LONG)) {
        return Long.MIN_VALUE;
    } else if (type.equals(InternalTypes.FLOAT)) {
        return Float.MIN_VALUE;
    } else if (type.equals(InternalTypes.DOUBLE)) {
        return Double.MIN_VALUE;
    } else if (type.equals(InternalTypes.STRING)) {
        return BinaryString.fromString("");
    } else if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        return Decimal.fromBigDecimal(new BigDecimal(Integer.MIN_VALUE), decimalType.precision(),
                decimalType.scale());/* ww  w. ja  v  a2s  .c  om*/
    } else if (type instanceof ArrayType) {
        byte[] bytes = new byte[rnd.nextInt(7) + 1];
        rnd.nextBytes(bytes);
        BinaryArray array = BinaryArray.fromPrimitiveArray(bytes);
        for (int i = 0; i < bytes.length; i++) {
            array.setNullByte(i);
        }
        return array;
    } else if (type.equals(InternalTypes.BINARY)) {
        byte[] bytes = new byte[rnd.nextInt(7) + 1];
        rnd.nextBytes(bytes);
        return bytes;
    } else if (type instanceof RowType) {
        return GenericRow.of(new Object[] { null });
    } else if (type instanceof GenericType) {
        return new BinaryGeneric<>(rnd.nextInt(), IntSerializer.INSTANCE);
    } else {
        throw new RuntimeException("Not support!");
    }
}

From source file:org.apache.flink.table.codegen.SortCodeGeneratorTest.java

private Object value3(InternalType type, Random rnd) {
    if (type.equals(InternalTypes.BOOLEAN)) {
        return true;
    } else if (type.equals(InternalTypes.BYTE)) {
        return Byte.MAX_VALUE;
    } else if (type.equals(InternalTypes.SHORT)) {
        return Short.MAX_VALUE;
    } else if (type.equals(InternalTypes.INT)) {
        return Integer.MAX_VALUE;
    } else if (type.equals(InternalTypes.LONG)) {
        return Long.MAX_VALUE;
    } else if (type.equals(InternalTypes.FLOAT)) {
        return Float.MAX_VALUE;
    } else if (type.equals(InternalTypes.DOUBLE)) {
        return Double.MAX_VALUE;
    } else if (type.equals(InternalTypes.STRING)) {
        return BinaryString.fromString(RandomStringUtils.random(100));
    } else if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        return Decimal.fromBigDecimal(new BigDecimal(Integer.MAX_VALUE), decimalType.precision(),
                decimalType.scale());//w ww  .  j a  v a2  s .  c om
    } else if (type instanceof ArrayType || type.equals(InternalTypes.BINARY)) {
        byte[] bytes = new byte[rnd.nextInt(100) + 100];
        rnd.nextBytes(bytes);
        return type.equals(InternalTypes.BINARY) ? bytes : BinaryArray.fromPrimitiveArray(bytes);
    } else if (type instanceof RowType) {
        RowType rowType = (RowType) type;
        if (rowType.getTypeAt(0).equals(InternalTypes.INT)) {
            return GenericRow.of(rnd.nextInt());
        } else {
            return GenericRow.of(GenericRow.of(rnd.nextInt()));
        }
    } else if (type instanceof GenericType) {
        return new BinaryGeneric<>(rnd.nextInt(), IntSerializer.INSTANCE);
    } else {
        throw new RuntimeException("Not support!");
    }
}

From source file:org.apache.hadoop.hbase.regionserver.TestHRegionReplayEvents.java

/**
 * Tests replaying region open markers from primary region. Checks whether the files are picked up
 *///w ww  . j ava2  s  . co  m
@Test
public void testReplayBulkLoadEvent() throws IOException {
    LOG.info("testReplayBulkLoadEvent starts");
    putDataWithFlushes(primaryRegion, 100, 0, 100); // no flush

    // close the region and open again.
    primaryRegion.close();
    primaryRegion = HRegion.openHRegion(rootDir, primaryHri, htd, walPrimary, CONF, rss, null);

    // bulk load a file into primary region
    Random random = new Random();
    byte[] randomValues = new byte[20];
    random.nextBytes(randomValues);
    Path testPath = TEST_UTIL.getDataTestDirOnTestFS();

    List<Pair<byte[], String>> familyPaths = new ArrayList<Pair<byte[], String>>();
    int expectedLoadFileCount = 0;
    for (byte[] family : families) {
        familyPaths
                .add(new Pair<byte[], String>(family, createHFileForFamilies(testPath, family, randomValues)));
        expectedLoadFileCount++;
    }
    primaryRegion.bulkLoadHFiles(familyPaths, false, null);

    // now replay the edits and the bulk load marker
    reader = createWALReaderForPrimary();

    LOG.info("-- Replaying edits and region events in secondary");
    BulkLoadDescriptor bulkloadEvent = null;
    while (true) {
        WAL.Entry entry = reader.next();
        if (entry == null) {
            break;
        }
        bulkloadEvent = WALEdit.getBulkLoadDescriptor(entry.getEdit().getCells().get(0));
        if (bulkloadEvent != null) {
            break;
        }
    }

    // we should have 1 bulk load event
    assertTrue(bulkloadEvent != null);
    assertEquals(expectedLoadFileCount, bulkloadEvent.getStoresCount());

    // replay the bulk load event
    secondaryRegion.replayWALBulkLoadEventMarker(bulkloadEvent);

    List<String> storeFileName = new ArrayList<String>();
    for (StoreDescriptor storeDesc : bulkloadEvent.getStoresList()) {
        storeFileName.addAll(storeDesc.getStoreFileList());
    }
    // assert that the bulk loaded files are picked
    for (Store s : secondaryRegion.getStores()) {
        for (StoreFile sf : s.getStorefiles()) {
            storeFileName.remove(sf.getPath().getName());
        }
    }
    assertTrue("Found some store file isn't loaded:" + storeFileName, storeFileName.isEmpty());

    LOG.info("-- Verifying edits from secondary");
    for (byte[] family : families) {
        assertGet(secondaryRegion, family, randomValues);
    }
}

From source file:org.apache.hadoop.hdfs.TestFileAppend4.java

/**
 * Corrupt all of the blocks in the blocksBeingWritten dir
 * for the specified datanode number. The corruption is
 * specifically the last checksum chunk of the file being
 * modified by writing random data into it.
 *//*from ww  w .j a v  a  2 s  .  c o m*/
private void corruptDataNode(int dnNumber, CorruptionType type) throws Exception {
    // get the FS data of the specified datanode
    File data_dir = new File(System.getProperty("test.build.data"),
            "dfs/data/data" + Integer.toString(dnNumber * 2 + 1) + "/blocksBeingWritten");
    int corrupted = 0;
    for (File block : data_dir.listFiles()) {
        // only touch the actual data, not the metadata (with CRC)
        if (block.getName().startsWith("blk_") && !block.getName().endsWith("meta")) {
            if (type == CorruptionType.CORRUPT_LAST_CHUNK) {
                RandomAccessFile file = new RandomAccessFile(block, "rw");
                FileChannel channel = file.getChannel();
                Random r = new Random();
                long lastBlockSize = channel.size() % 512;
                long position = channel.size() - lastBlockSize;
                int length = r.nextInt((int) (channel.size() - position + 1));
                byte[] buffer = new byte[length];
                r.nextBytes(buffer);

                channel.write(ByteBuffer.wrap(buffer), position);
                System.out.println("Deliberately corrupting file " + block.getName() + " at offset " + position
                        + " length " + length);
                file.close();

            } else if (type == CorruptionType.TRUNCATE_BLOCK_TO_ZERO) {
                LOG.info("Truncating block file at " + block);
                RandomAccessFile blockFile = new RandomAccessFile(block, "rw");
                blockFile.setLength(0);
                blockFile.close();

                RandomAccessFile metaFile = new RandomAccessFile(FSDataset.findMetaFile(block), "rw");
                metaFile.setLength(0);
                metaFile.close();
            } else if (type == CorruptionType.TRUNCATE_BLOCK_HALF) {
                FSDatasetTestUtil.truncateBlockFile(block, block.length() / 2);
            } else {
                assert false;
            }
            ++corrupted;
        }
    }
    assertTrue("Should have some data in bbw to corrupt", corrupted > 0);
}

From source file:com.evolveum.polygon.connector.ldap.schema.AbstractSchemaTranslator.java

private String hashBytes(byte[] clear, String alg, long seed) {
    MessageDigest md = null;/*from  w w  w .j a va2  s  .c  o  m*/

    try {
        if (alg.equalsIgnoreCase("SSHA") || alg.equalsIgnoreCase("SHA")) {
            md = MessageDigest.getInstance("SHA-1");
        } else if (alg.equalsIgnoreCase("SMD5") || alg.equalsIgnoreCase("MD5")) {
            md = MessageDigest.getInstance("MD5");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new ConnectorException("Could not find MessageDigest algorithm: " + alg);
    }

    if (md == null) {
        throw new ConnectorException("Unsupported MessageDigest algorithm: " + alg);
    }

    byte[] salt = {};
    if (alg.equalsIgnoreCase("SSHA") || alg.equalsIgnoreCase("SMD5")) {
        Random rnd = new Random();
        rnd.setSeed(System.currentTimeMillis() + seed);
        salt = new byte[8];
        rnd.nextBytes(salt);
    }

    md.reset();
    md.update(clear);
    md.update(salt);
    byte[] hash = md.digest();

    byte[] hashAndSalt = new byte[hash.length + salt.length];
    System.arraycopy(hash, 0, hashAndSalt, 0, hash.length);
    System.arraycopy(salt, 0, hashAndSalt, hash.length, salt.length);

    StringBuilder resSb = new StringBuilder(alg.length() + hashAndSalt.length);
    resSb.append('{');
    resSb.append(alg);
    resSb.append('}');
    resSb.append(Base64.encode(hashAndSalt));

    return resSb.toString();
}

From source file:org.ejbca.ra.EnrollMakeNewRequestBean.java

/**
 * Adds end entity and creates its token that will be downloaded. This method is responsible for deleting the end entity if something goes wrong with token creation.
 * @param tokenType the type of the token that will be created (one of: TOKEN_USERGEN, TOKEN_SOFT_P12, TOKEN_SOFT_JKS from EndEntityConstants)
 * @param tokenName the name of the token. It will be used only in messages and logs
 * @param tokenDownloadType the download type/format of the token. This is used only with TOKEN_USERGEN since this is the only one that have different formats: PEM, DER,...)
 * @return generated token as byte array or null if token could not be generated
 *//*from  w ww. j  a v a  2s . c  om*/
private byte[] addEndEntityAndGenerateToken(int tokenType, String tokenName,
        TokenDownloadType tokenDownloadType) {
    //Update the EndEntityInformation data
    getSubjectDn().update();
    getSubjectAlternativeName().update();
    getSubjectDirectoryAttributes().update();

    //Fill End Entity information
    final EndEntityInformation endEntityInformation = getEndEntityInformation();
    endEntityInformation.setCAId(getCAInfo().getCAId());
    endEntityInformation.setCardNumber(""); //TODO Card Number
    endEntityInformation.setCertificateProfileId(
            authorizedCertificateProfiles.get(Integer.parseInt(getSelectedCertificateProfile())).getId());
    endEntityInformation.setDN(getSubjectDn().toString());
    endEntityInformation.setEndEntityProfileId(
            authorizedEndEntityProfiles.get(Integer.parseInt(getSelectedEndEntityProfile())).getId());
    endEntityInformation.setExtendedinformation(new ExtendedInformation());//TODO don't know anything about it...
    endEntityInformation.setHardTokenIssuerId(0); //TODO not sure....
    endEntityInformation.setKeyRecoverable(false); //TODO not sure...
    endEntityInformation.setPrintUserData(false); // TODO not sure...
    endEntityInformation.setStatus(EndEntityConstants.STATUS_NEW);
    endEntityInformation.setSubjectAltName(getSubjectAlternativeName().toString());
    endEntityInformation.setTimeCreated(new Date());
    endEntityInformation.setTimeModified(new Date());
    endEntityInformation.setType(new EndEntityType(EndEntityTypes.ENDUSER));
    // sendnotification must be set after setType, because it adds to the type
    endEntityInformation.setSendNotification(
            getEndEntityProfile().getValue(EndEntityProfile.SENDNOTIFICATION, 0).equals(EndEntityProfile.TRUE)
                    && !endEntityInformation.getSendNotification());
    endEntityInformation.setTokenType(tokenType);

    // Fill end-entity information (Username and Password)
    final byte[] randomData = new byte[16];
    final Random random = new SecureRandom();
    random.nextBytes(randomData);
    if (StringUtils.isBlank(endEntityInformation.getUsername())) {
        String autousername = new String(Hex.encode(randomData));
        while (raMasterApiProxyBean.searchUser(raAuthenticationBean.getAuthenticationToken(),
                autousername) != null) {
            if (log.isDebugEnabled()) {
                log.debug("Autogenerated username '" + autousername
                        + "' is already reserved. Generating the new one...");
            }
            random.nextBytes(randomData);
            autousername = new String(Hex.encode(randomData));
        }
        if (log.isDebugEnabled()) {
            log.debug("Unique username '" + autousername + "' has been generated");
        }
        endEntityInformation.setUsername(autousername);
    }
    if (getEndEntityProfile().useAutoGeneratedPasswd()) {
        // If auto-generated passwords are used, this is set on the CA side when adding or changing the EE as long as the password is null 
        endEntityInformation.setPassword(null);
    } else if (StringUtils.isEmpty(endEntityInformation.getPassword())) {
        // If not needed just use some random data
        random.nextBytes(randomData);
        endEntityInformation
                .setPassword(new String(Hex.encode(CertTools.generateSHA256Fingerprint(randomData))));
    }

    //Fill end-entity information (KeyStoreAlgorithm* or CertificateRequest)
    if (KeyPairGeneration.ON_SERVER.equals(getSelectedKeyPairGenerationEnum())) {
        final String[] tokenKeySpecSplit = getSelectedAlgorithm().split("_");
        endEntityInformation.getExtendedinformation().setKeyStoreAlgorithmType(tokenKeySpecSplit[0]);
        endEntityInformation.getExtendedinformation().setKeyStoreAlgorithmSubType(tokenKeySpecSplit[1]);
    } else if (KeyPairGeneration.PROVIDED_BY_USER.equals(getSelectedKeyPairGenerationEnum())) {
        try {
            endEntityInformation.getExtendedinformation().setCertificateRequest(
                    CertTools.getCertificateRequestFromPem(getCertificateRequest()).getEncoded());
        } catch (IOException e) {
            raLocaleBean.addMessageError("enroll_invalid_certificate_request");
            return null;
        }
    }

    //Add end-entity
    try {
        if (raMasterApiProxyBean.addUser(raAuthenticationBean.getAuthenticationToken(), endEntityInformation,
                /*clearpwd=*/false)) {
            log.info("End entity with username " + endEntityInformation.getUsername()
                    + " has been successfully added");
        } else {
            raLocaleBean.addMessageInfo("enroll_end_entity_could_not_be_added",
                    endEntityInformation.getUsername());
            log.info("Certificate could not be generated for end entity with username "
                    + endEntityInformation.getUsername());
            return null;
        }
    } catch (AuthorizationDeniedException e) {
        raLocaleBean.addMessageInfo("enroll_unauthorized_operation", e.getMessage());
        log.info("You are not authorized to execute this operation", e);
        return null;
    } catch (WaitingForApprovalException e) {
        requestId = e.getRequestId();
        log.info("Request with ID " + requestId + " is still waiting for approval");
        return null;
    } catch (EjbcaException e) {
        ErrorCode errorCode = EjbcaException.getErrorCode(e);
        if (errorCode != null) {
            if (errorCode.equals(ErrorCode.USER_ALREADY_EXISTS)) {
                raLocaleBean.addMessageError("enroll_username_already_exists",
                        endEntityInformation.getUsername());
                log.info("The username " + endEntityInformation.getUsername() + " already exists");
            } else {
                raLocaleBean.addMessageError(errorCode);
                log.info("EjbcaException has been caught. Error Code: " + errorCode, e);
            }
        } else {
            raLocaleBean.addMessageError("enroll_end_entity_could_not_be_added",
                    endEntityInformation.getUsername(), e.getMessage());
            log.info("End entity with username " + endEntityInformation.getUsername()
                    + " could not be added. Contact your administrator or check the logs.", e);
        }
        return null;
    }

    //The end-entity has been added now! Make sure clean-up is done in this "try-finally" block if something goes wrong
    try {
        //Generates a keystore token if user has specified "ON SERVER" key pair generation.
        //Generates a certificate token if user has specified "PROVIDED_BY_USER" key pair generation
        byte[] ret = null;
        if (KeyPairGeneration.ON_SERVER.equals(getSelectedKeyPairGenerationEnum())) {
            try {
                ret = raMasterApiProxyBean.generateKeyStore(raAuthenticationBean.getAuthenticationToken(),
                        endEntityInformation);
            } catch (AuthorizationDeniedException e) {
                raLocaleBean.addMessageInfo("enroll_unauthorized_operation", e.getMessage());
                log.info("You are not authorized to execute this operation", e);
            } catch (EjbcaException e) {
                ErrorCode errorCode = EjbcaException.getErrorCode(e);
                if (errorCode != null) {
                    if (errorCode.equals(
                            ErrorCode.CERTIFICATE_WITH_THIS_SUBJECTDN_ALREADY_EXISTS_FOR_ANOTHER_USER)) {
                        raLocaleBean.addMessageError("enroll_subject_dn_already_exists_for_another_user",
                                subjectDn.getValue());
                        log.info("Subject DN " + subjectDn.getValue() + " already exists for another user", e);
                    } else if (errorCode.equals(ErrorCode.LOGIN_ERROR)) {
                        raLocaleBean.addMessageError("enroll_keystore_could_not_be_generated",
                                endEntityInformation.getUsername(), errorCode);
                        log.info(
                                "Keystore could not be generated for user " + endEntityInformation.getUsername()
                                        + ": " + e.getMessage() + ", " + errorCode);
                    } else {
                        raLocaleBean.addMessageError(errorCode);
                        log.info("Exception creating keystore. Error Code: " + errorCode, e);
                    }
                } else {
                    raLocaleBean.addMessageError("enroll_keystore_could_not_be_generated",
                            endEntityInformation.getUsername(), e.getMessage());
                    log.info("Keystore could not be generated for user " + endEntityInformation.getUsername()
                            + ": " + e.getMessage());
                }
            } catch (Exception e) {
                raLocaleBean.addMessageError("enroll_keystore_could_not_be_generated",
                        endEntityInformation.getUsername(), e.getMessage());
                log.info("Keystore could not be generated for user " + endEntityInformation.getUsername() + ": "
                        + e.getMessage());
            }
        } else if (KeyPairGeneration.PROVIDED_BY_USER.equals(getSelectedKeyPairGenerationEnum())) {
            try {
                endEntityInformation.getExtendedinformation().setCertificateRequest(
                        CertTools.getCertificateRequestFromPem(getCertificateRequest()).getEncoded());
                final byte[] certificateDataToDownload = raMasterApiProxyBean
                        .createCertificate(raAuthenticationBean.getAuthenticationToken(), endEntityInformation);
                if (certificateDataToDownload == null) {
                    raLocaleBean.addMessageError("enroll_certificate_could_not_be_generated",
                            endEntityInformation.getUsername(), "null");
                    log.info("Certificate could not be generated for end entity with username "
                            + endEntityInformation.getUsername() + ": null");
                } else if (tokenDownloadType == TokenDownloadType.PEM_FULL_CHAIN) {
                    X509Certificate certificate = CertTools.getCertfromByteArray(certificateDataToDownload,
                            X509Certificate.class);
                    LinkedList<Certificate> chain = new LinkedList<Certificate>(
                            getCAInfo().getCertificateChain());
                    chain.addFirst(certificate);
                    ret = CertTools.getPemFromCertificateChain(chain);
                } else if (tokenDownloadType == TokenDownloadType.PKCS7) {
                    X509Certificate certificate = CertTools.getCertfromByteArray(certificateDataToDownload,
                            X509Certificate.class);
                    LinkedList<Certificate> chain = new LinkedList<Certificate>(
                            getCAInfo().getCertificateChain());
                    chain.addFirst(certificate);
                    ret = CertTools.getPemFromPkcs7(
                            CertTools.createCertsOnlyCMS(CertTools.convertCertificateChainToX509Chain(chain)));
                } else if (tokenDownloadType == TokenDownloadType.PEM) {
                    X509Certificate certificate = CertTools.getCertfromByteArray(certificateDataToDownload,
                            X509Certificate.class);
                    ret = CertTools.getPemFromCertificateChain(Arrays.asList((Certificate) certificate));
                } else {
                    ret = certificateDataToDownload;
                }
            } catch (AuthorizationDeniedException e) {
                raLocaleBean.addMessageInfo("enroll_unauthorized_operation", e.getMessage());
                log.info("You are not authorized to execute this operation", e);
            } catch (EjbcaException | CertificateEncodingException | CertificateParsingException
                    | ClassCastException | CMSException | IOException e) {
                ErrorCode errorCode = EjbcaException.getErrorCode(e);
                if (errorCode != null) {
                    if (errorCode.equals(
                            ErrorCode.CERTIFICATE_WITH_THIS_SUBJECTDN_ALREADY_EXISTS_FOR_ANOTHER_USER)) {
                        raLocaleBean.addMessageError("enroll_subject_dn_already_exists_for_another_user",
                                subjectDn.getValue());
                        log.info("Subject DN " + subjectDn.getValue() + " already exists for another user", e);
                    } else if (errorCode.equals(ErrorCode.LOGIN_ERROR)) {
                        raLocaleBean.addMessageError("enroll_certificate_could_not_be_generated",
                                endEntityInformation.getUsername(), errorCode);
                        log.info("Certificate could not be generated for user "
                                + endEntityInformation.getUsername() + ": " + e.getMessage() + ", "
                                + errorCode);
                    } else {
                        raLocaleBean.addMessageError(errorCode);
                        log.info("Exception creating certificate. Error Code: " + errorCode, e);
                    }
                } else {
                    raLocaleBean.addMessageError("enroll_certificate_could_not_be_generated",
                            endEntityInformation.getUsername(), e.getMessage());
                    log.info("Certificate could not be generated for end entity with username "
                            + endEntityInformation.getUsername(), e);
                }
            }
        }
        return ret;
    } finally {
        //End entity clean-up must be done if enrollment could not be completed (but end-entity has been added)
        try {
            EndEntityInformation fromCA = raMasterApiProxyBean.searchUser(
                    raAuthenticationBean.getAuthenticationToken(), endEntityInformation.getUsername());
            if (fromCA != null && fromCA.getStatus() != EndEntityConstants.STATUS_GENERATED) {
                raMasterApiProxyBean.deleteUser(raAuthenticationBean.getAuthenticationToken(),
                        endEntityInformation.getUsername());
            }
        } catch (AuthorizationDeniedException e) {
            throw new IllegalStateException(e);
        }
        endEntityInformation.setUsername("");
    }
}