Example usage for java.security SecureRandom getInstance

List of usage examples for java.security SecureRandom getInstance

Introduction

In this page you can find the example usage for java.security SecureRandom getInstance.

Prototype

public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.

Usage

From source file:org.b3log.latke.util.Crypts.java

/**
 * Decrypts by AES./*from   www.  j a va2  s .  c  o  m*/
 *
 * @param content the specified content to decrypt
 * @param key     the specified key
 * @return original content
 * @see #encryptByAES(java.lang.String, java.lang.String)
 */
public static String decryptByAES(final String content, final String key) {
    try {
        final byte[] data = Hex.decodeHex(content.toCharArray());
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);
        final SecretKey secretKey = kgen.generateKey();
        final byte[] enCodeFormat = secretKey.getEncoded();
        final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
        final Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        final byte[] result = cipher.doFinal(data);

        return new String(result, "UTF-8");
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Decrypt failed");

        return null;
    }
}

From source file:piecework.security.concrete.DefaultEncryptionKeyProvider.java

@PostConstruct
public void init() throws GeneralSecurityException, UnsupportedEncodingException {
    String encryptionPseudoRandomGenerator = environment.getProperty("encryption.pseudorandom.generator");
    if (StringUtils.isNotEmpty(encryptionPseudoRandomGenerator))
        this.random = SecureRandom.getInstance(encryptionPseudoRandomGenerator);
    else/*from   w w w  .j  av a  2s.  c  o m*/
        this.random = new SecureRandom();

    String seed = environment.getProperty("encryption.key.seed");
    if (StringUtils.isNotEmpty(seed))
        this.random.setSeed(Base64.decode(seed.getBytes("UTF-8")));

    // These are keys that will be used to encrypt new data
    String encryptionKeysActive = environment.getProperty("encryption.keys.active");
    // These are keys that will be consulted when decrypting data -- allowing keys
    // to be deactivated for future use without having to migrate all existing data
    // to one of the newer keys
    String encryptionKeysHistoric = environment.getProperty("encryption.keys.historic");

    Map<String, SecretKey> activeKeyMap = parseKeys(encryptionKeysActive);
    encryptKeyNames.addAll(activeKeyMap.keySet());
    encryptKeyMap.putAll(activeKeyMap);

    Map<String, SecretKey> historicKeyMap = parseKeys(encryptionKeysHistoric);
    decryptKeyMap.putAll(activeKeyMap);
    decryptKeyMap.putAll(historicKeyMap);
}

From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

public void generateKeys(OutputStream publicKeyOut, OutputStream privateKeyOut)
        throws GeneralSecurityException, IOException {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    generator.initialize(KEY_SIZE * 8, random);

    KeyPair keyPair = generator.generateKeyPair();

    OutputStream privateOut = new Base64OutputStream(privateKeyOut);
    PrivateKey privateKey = keyPair.getPrivate();
    privateOut.write(privateKey.getEncoded());
    IOUtil.close(privateOut);//ww w  . j  a v a 2  s . c  o m

    OutputStream publicOut = new Base64OutputStream(publicKeyOut);
    PublicKey publicKey = keyPair.getPublic();
    publicOut.write(publicKey.getEncoded());
    IOUtil.close(publicOut);
}

From source file:org.sakaiproject.nakamura.api.activity.ActivityUtils.java

/**
 * @return Creates a unique path to an activity in the form of 2010-01-21-09-randombit
 *//* w  w  w .j  a va  2s  . c  om*/
public static String createId() {
    Calendar c = Calendar.getInstance();

    String[] vals = new String[4];
    vals[0] = "" + c.get(Calendar.YEAR);
    vals[1] = StringUtils.leftPad("" + (c.get(Calendar.MONTH) + 1), 2, "0");
    vals[2] = StringUtils.leftPad("" + c.get(Calendar.DAY_OF_MONTH), 2, "0");
    vals[3] = StringUtils.leftPad("" + c.get(Calendar.HOUR_OF_DAY), 2, "0");

    StringBuilder id = new StringBuilder();

    for (String v : vals) {
        id.append(v).append("-");
    }

    byte[] bytes = new byte[20];
    String randomHash = "";
    try {
        if (random == null) {
            random = SecureRandom.getInstance("SHA1PRNG");
        }
        random.nextBytes(bytes);
        randomHash = Arrays.toString(bytes);
        randomHash = org.sakaiproject.nakamura.util.StringUtils.sha1Hash(randomHash);
    } catch (NoSuchAlgorithmException e) {
    } catch (UnsupportedEncodingException e) {
    }

    id.append(randomHash);
    return id.toString();
}

From source file:org.psikeds.common.idgen.impl.RandomStringGenerator.java

/**
 * @param randomAlgorithm/*from   w  ww  . j  av a  2  s  .c  om*/
 *          the randomAlgorithm to set
 */
public void setRandomAlgorithm(final String randomAlgorithm) throws NoSuchAlgorithmException {
    if (StringUtils.isEmpty(randomAlgorithm)) {
        throw new NoSuchAlgorithmException();
    }
    if ((this.secran == null) || !randomAlgorithm.equals(this.randomAlgorithm)) {
        this.secran = SecureRandom.getInstance(randomAlgorithm);
        this.randomAlgorithm = randomAlgorithm;
    }
}

From source file:org.sakaiproject.kernel.locking.LockManagerImpl.java

/**
 * @throws NoSuchAlgorithmException/*w w  w . j a  v  a  2  s  .c  o m*/
 * 
 */
@Inject
public LockManagerImpl(CacheManagerService cacheManagerService) throws NoSuchAlgorithmException {
    this.cacheManagerService = cacheManagerService;
    lockMap = cacheManagerService.getCache(LOCKMAP, CacheScope.CLUSTERREPLICATED);
    random = SecureRandom.getInstance("SHA1PRNG");
    instanceId = random.nextLong();
}

From source file:org.unitedid.auth.client.factors.PasswordFactor.java

public String getRandomNonce() throws NoSuchAlgorithmException {
    SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
    byte[] randomBytes = new byte[6];
    rand.nextBytes(randomBytes);//  w  w w.ja  va 2s. co m

    String result = "";
    for (int i = 0; i < randomBytes.length; i++) {
        result += Integer.toString((randomBytes[i] & 0xff) + 0x100, 16).substring(1);
    }

    return result;
}

From source file:edu.ku.brc.helpers.Encryption.java

/**
 * Encrypts the string from its array of bytes
 * @param input the actual string (in bytes) that is to be encrypted
 * @param password a password, which is really any string, but must be the same string that was used to decrypt it.
 * @return a byte array of the encrypted chars
 * @throws Exception in case something goes wrong
 *///from w w w .  java 2  s.  c o m
public static byte[] encrypt(byte[] input, char[] password) throws Exception {
    /*
     * Get ourselves a random number generator, needed in a number of places for encrypting.
     */
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$

    /*
     * A "salt" is considered an essential part of password-based encryption. The salt is
     * selected at random for each encryption. It is not considered "sensitive", so it is tacked
     * onto the generated ciphertext without any special processing. It doesn't matter if an
     * attacker actually gets the salt. The salt is used as part of the key, with the very
     * useful result that if you Encryption the same plaintext with the same password twice, you
     * get *different* ciphertexts. There are lots of pages on the 'net with information about
     * salts and password-based encryption, so read them if you want more details. Suffice to
     * say salt=good, no salt=bad.
     */
    byte[] salt = new byte[SALT_LENGTH];
    sr.nextBytes(salt);

    /*
     * We've now got enough information to build the actual key. We do this by encapsulating the
     * variables in a PBEKeySpec and using a SecretKeyFactory to transform the spec into a key.
     */
    PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
    SecretKey key = skf.generateSecret(keyspec);

    /*
     * We'll use a ByteArrayOutputStream to conveniently gather up data as it's encrypted.
     */
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /*
     * We've to a key, but to actually Encryption something, we need a "cipher". The cipher is
     * created, then initialized with the key, salt, and iteration count. We use a
     * PBEParameterSpec to hold the salt and iteration count needed by the Cipher object.
     */
    PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT);
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key, paramspec, sr);

    /*
     * First, in our output, we need to save the salt in plain unencrypted form.
     */
    baos.write(salt);

    /*
     * Next, Encryption our plaintext using the Cipher object, and write it into our output buffer.
     */
    baos.write(cipher.doFinal(input));

    /*
     * We're done. For security reasons, we probably want the PBEKeySpec object to clear its
     * internal copy of the password, so it can't be stolen later.
     */
    keyspec.clearPassword();
    return baos.toByteArray();
}

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

@Override
public String encryptData(final SecureToken data) {
    if (data == null || StringUtils.isBlank(data.getData())) {
        throw new IllegalArgumentException("missing token");
    }//www .ja va 2s .c o m
    try {
        final SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
        final int[] paddingSizes = computePaddingLengths(random);

        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        dataOutputStream.write(generatePadding(paddingSizes[0], random));
        dataOutputStream.writeUTF(data.getData());
        dataOutputStream.writeUTF(createChecksum(data.getData()));
        dataOutputStream.writeLong(data.getTimeStamp());
        dataOutputStream.write(generatePadding(paddingSizes[1], random));

        dataOutputStream.flush();
        final byte[] unsignedDataBytes = byteArrayOutputStream.toByteArray();

        final byte[] md5SigBytes = generateSignature(unsignedDataBytes, 0, unsignedDataBytes.length,
                signatureKeyBytes);
        byteArrayOutputStream.write(md5SigBytes);
        byteArrayOutputStream.flush();

        final byte[] signedDataBytes = byteArrayOutputStream.toByteArray();

        return encrypt(signedDataBytes, encryptionKeyBytes, random);
    } catch (final IOException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    } catch (final GeneralSecurityException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    }
}

From source file:com.turo.pushy.apns.ApnsClientBenchmark.java

@Setup
public void setUp() throws Exception {
    this.eventLoopGroup = new NioEventLoopGroup(2);

    final ApnsSigningKey signingKey;
    {//from w w  w  . ja v a 2  s .c  om
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        final SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

        keyPairGenerator.initialize(256, random);

        signingKey = new ApnsSigningKey(KEY_ID, TEAM_ID,
                (ECPrivateKey) keyPairGenerator.generateKeyPair().getPrivate());
    }

    final ApnsClientBuilder clientBuilder = new ApnsClientBuilder().setApnsServer(HOST, PORT)
            .setConcurrentConnections(this.concurrentConnections).setSigningKey(signingKey)
            .setTrustedServerCertificateChain(
                    ApnsClientBenchmark.class.getResourceAsStream(CA_CERTIFICATE_FILENAME))
            .setEventLoopGroup(this.eventLoopGroup);

    this.client = clientBuilder.build();
    this.server = new BenchmarkApnsServer(
            ApnsClientBenchmark.class.getResourceAsStream(SERVER_CERTIFICATES_FILENAME),
            ApnsClientBenchmark.class.getResourceAsStream(SERVER_KEY_FILENAME), this.eventLoopGroup);

    final String token = generateRandomToken();

    this.pushNotifications = new ArrayList<>(this.notificationCount);

    final ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder();

    for (int i = 0; i < this.notificationCount; i++) {
        final String payload = payloadBuilder
                .setAlertBody(RandomStringUtils.randomAlphanumeric(MESSAGE_BODY_LENGTH))
                .buildWithDefaultMaximumLength();

        this.pushNotifications.add(new SimpleApnsPushNotification(token, TOPIC, payload));
    }

    this.server.start(PORT).await();
}