Java Code Examples for java.security.SecureRandom

The following are top voted examples for showing how to use java.security.SecureRandom. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: kafka-0.11.0.0-src-with-comment   File: TestSslUtils.java   View source code 17 votes vote down vote up
public X509Certificate generate(String dn, KeyPair keyPair) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);

        if (subjectAltName != null)
            v3CertGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
        X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
 
Example 2
Project: AppCoins-ethereumj   File: ECKey.java   View source code 7 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 *
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
    this.provider = provider;

    final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
    final KeyPair keyPair = keyPairGen.generateKeyPair();

    this.privKey = keyPair.getPrivate();

    final PublicKey pubKey = keyPair.getPublic();
    if (pubKey instanceof BCECPublicKey) {
        pub = ((BCECPublicKey) pubKey).getQ();
    } else if (pubKey instanceof ECPublicKey) {
        pub = extractPublicKey((ECPublicKey) pubKey);
    } else {
        throw new AssertionError(
            "Expected Provider " + provider.getName() +
            " to produce a subtype of ECPublicKey, found " + pubKey.getClass());
    }
}
 
Example 3
Project: AppCoins-ethereumj   File: ECKey.java   View source code 7 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 *
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
    this.provider = provider;

    final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
    final KeyPair keyPair = keyPairGen.generateKeyPair();

    this.privKey = keyPair.getPrivate();
    final PublicKey pubKey = keyPair.getPublic();

    if (pubKey instanceof BCECPublicKey) {
        pub = ((BCECPublicKey) pubKey).getQ();
    } else if (pubKey instanceof ECPublicKey) {
        pub = extractPublicKey((ECPublicKey) pubKey);
    } else {
        throw new AssertionError(
            "Expected Provider " + provider.getName() +
            " to produce a subtype of ECPublicKey, found " + pubKey.getClass());
    }
}
 
Example 4
Project: osc-core   File: SslContextProvider.java   View source code 6 votes vote down vote up
private SslContextProvider() {
    // load SSL context
    TrustManager[] trustManager = new TrustManager[]{X509TrustManagerFactory.getInstance()};
    try {
        this.sslContext = SSLContext.getInstance("TLSv1.2");
        this.sslContext.init(null, trustManager, new SecureRandom());

        // disable SSL session caching - we load SSL certificates dinamically so we need to ensure
        // that we have up to date cached certificates list
        this.sslContext.getClientSessionContext().setSessionCacheSize(1);
        this.sslContext.getClientSessionContext().setSessionTimeout(1);
        this.sslContext.getServerSessionContext().setSessionCacheSize(1);
        this.sslContext.getServerSessionContext().setSessionTimeout(1);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        LOG.error("Encountering security exception in SSL context", e);
        throw new RuntimeException("Internal error with SSL context", e);
    }
}
 
Example 5
Project: FirefoxData-android   File: BaseResource.java   View source code 6 votes vote down vote up
private static ClientConnectionManager enableTLSConnectionManager() throws KeyManagementException, NoSuchAlgorithmException  {
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, null, new SecureRandom());

  Logger.debug(LOG_TAG, "Using protocols and cipher suites for Android API " + android.os.Build.VERSION.SDK_INT);
  SSLSocketFactory sf = new SSLSocketFactory(sslContext, GlobalConstants.DEFAULT_PROTOCOLS, GlobalConstants.DEFAULT_CIPHER_SUITES, null);
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(new Scheme("https", 443, sf));
  schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
  ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);

  cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
  cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
  connManager = cm;
  return cm;
}
 
Example 6
Project: os   File: DESUtils.java   View source code 6 votes vote down vote up
/**
 * DES加密
 * 
 * @author : chenssy
 * @date : 2016年5月20日 下午5:51:37
 *
 * @param data
 * 				待加密字符串
 * @param key
 * 				校验位
 * @return
 */
   @SuppressWarnings("restriction")
protected static String encrypt(String data,String key) {  
       String encryptedData = null;  
       try {  
           // DES算法要求有一个可信任的随机数源  
           SecureRandom sr = new SecureRandom();  
           DESKeySpec deskey = new DESKeySpec(key.getBytes());  
           // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象  
           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
           SecretKey secretKey = keyFactory.generateSecret(deskey);  
           // 加密对象  
           Cipher cipher = Cipher.getInstance("DES");  
           cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);  
           // 加密,并把字节数组编码成字符串  
           encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));  
       } catch (Exception e) {  
           throw new RuntimeException("加密错误,错误信息:", e);  
       }  
       return encryptedData;  
   }
 
Example 7
Project: GitHub   File: sectionZeroAdapter.java   View source code 6 votes vote down vote up
@Override
protected void withBindHolder(itemCommonBinder holder, String data, int position) {
    holder.textViewSample.setText(data + "just the sample data");
    holder.item_view.setBackgroundColor(Color.parseColor("#AAffffff"));
    SecureRandom imgGen = new SecureRandom();
    switch (imgGen.nextInt(3)) {
        case 0:
            holder.imageViewSample.setImageResource(R.drawable.scn1);
            break;
        case 1:
            holder.imageViewSample.setImageResource(R.drawable.jr13);
            break;
        case 2:
            holder.imageViewSample.setImageResource(R.drawable.jr16);
            break;
    }
}
 
Example 8
Project: creacoinj   File: WalletTool.java   View source code 6 votes vote down vote up
private static void marry() {
    if (!options.has(xpubkeysFlag)) {
        throw new IllegalStateException();
    }

    String[] xpubkeys = options.valueOf(xpubkeysFlag).split(",");
    ImmutableList.Builder<DeterministicKey> keys = ImmutableList.builder();
    for (String xpubkey : xpubkeys) {
        keys.add(DeterministicKey.deserializeB58(null, xpubkey.trim(), params));
    }
    MarriedKeyChain chain = MarriedKeyChain.builder()
            .random(new SecureRandom())
            .followingKeys(keys.build())
            .build();
    wallet.addAndActivateHDChain(chain);
}
 
Example 9
Project: ipack   File: TlsClientProtocol.java   View source code 6 votes vote down vote up
private static SecureRandom createSecureRandom()
{
    /*
     * We use our threaded seed generator to generate a good random seed. If the user has a
     * better random seed, he should use the constructor with a SecureRandom.
     */
    ThreadedSeedGenerator tsg = new ThreadedSeedGenerator();
    SecureRandom random = new SecureRandom();

    /*
     * Hopefully, 20 bytes in fast mode are good enough.
     */
    random.setSeed(tsg.generateSeed(20, true));

    return random;
}
 
Example 10
Project: strongbox   File: EncryptionPayload.java   View source code 6 votes vote down vote up
@JsonCreator
public EncryptionPayload(@JsonProperty("value") SecretValue value,
                         @JsonProperty("userdata") Optional<UserData> userData,
                         @JsonProperty("created") ZonedDateTime created,
                         Optional<UserAlias> createdBy,
                         @JsonProperty("modified") ZonedDateTime modified,
                         Optional<UserAlias> modifiedBy,
                         @JsonProperty("comment") Optional<Comment> comment) {

    this.value = value;
    this.userData = userData;
    this.created = created;
    this.modified = modified;
    this.createdBy = createdBy;
    this.modifiedBy = modifiedBy;
    this.comment = comment;

    try {
        this.random = SecureRandom.getInstanceStrong();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to instantiate random number generator", e);
    }
}
 
Example 11
Project: ipack   File: ECNRSigner.java   View source code 6 votes vote down vote up
public void init(
    boolean          forSigning, 
    CipherParameters param) 
{
    this.forSigning = forSigning;
    
    if (forSigning)
    {
        if (param instanceof ParametersWithRandom)
        {
            ParametersWithRandom    rParam = (ParametersWithRandom)param;

            this.random = rParam.getRandom();
            this.key = (ECPrivateKeyParameters)rParam.getParameters();
        }
        else
        {
            this.random = new SecureRandom();
            this.key = (ECPrivateKeyParameters)param;
        }
    }
    else
    {
        this.key = (ECPublicKeyParameters)param;
    }
}
 
Example 12
Project: ipack   File: KeyPairGeneratorSpi.java   View source code 6 votes vote down vote up
public void initialize(
    int strength,
    SecureRandom random)
{
    this.random = random;

    if (ecParams != null)
    {
        try
        {
            initialize((ECGenParameterSpec)ecParams, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new InvalidParameterException("key size not configurable.");
        }
    }
    else
    {
        throw new InvalidParameterException("unknown key size.");
    }
}
 
Example 13
Project: ipack   File: KeyPairGeneratorSpi.java   View source code 6 votes vote down vote up
public void initialize(
    AlgorithmParameterSpec params,
    SecureRandom random)
    throws InvalidAlgorithmParameterException
{
    if (!(params instanceof DHParameterSpec))
    {
        throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec");
    }
    DHParameterSpec dhParams = (DHParameterSpec)params;

    param = new DHKeyGenerationParameters(random, new DHParameters(dhParams.getP(), dhParams.getG(), null, dhParams.getL()));

    engine.init(param);
    initialised = true;
}
 
Example 14
Project: ipack   File: IESCipher.java   View source code 6 votes vote down vote up
public void engineInit(
    int opmode,
    Key key,
    AlgorithmParameters params,
    SecureRandom random)
    throws InvalidKeyException, InvalidAlgorithmParameterException
{
    AlgorithmParameterSpec paramSpec = null;

    if (params != null)
    {
        try
        {
            paramSpec = params.getParameterSpec(IESParameterSpec.class);
        }
        catch (Exception e)
        {
            throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString());
        }
    }

    engineParam = params;
    engineInit(opmode, key, paramSpec, random);
}
 
Example 15
Project: ipack   File: NTRUEncryptionKeyGenerationParameters.java   View source code 6 votes vote down vote up
/**
 * Constructs a parameter set that uses ternary private keys (i.e. </code>polyType=SIMPLE</code>).
 *
 * @param N            number of polynomial coefficients
 * @param q            modulus
 * @param df           number of ones in the private polynomial <code>f</code>
 * @param dm0          minimum acceptable number of -1's, 0's, and 1's in the polynomial <code>m'</code> in the last encryption step
 * @param db           number of random bits to prepend to the message
 * @param c            a parameter for the Index Generation Function ({@link org.bouncycastle.pqc.crypto.ntru.IndexGenerator})
 * @param minCallsR    minimum number of hash calls for the IGF to make
 * @param minCallsMask minimum number of calls to generate the masking polynomial
 * @param hashSeed     whether to hash the seed in the MGF first (true) or use the seed directly (false)
 * @param oid          three bytes that uniquely identify the parameter set
 * @param sparse       whether to treat ternary polynomials as sparsely populated ({@link org.bouncycastle.pqc.math.ntru.polynomial.SparseTernaryPolynomial} vs {@link org.bouncycastle.pqc.math.ntru.polynomial.DenseTernaryPolynomial})
 * @param fastFp       whether <code>f=1+p*F</code> for a ternary <code>F</code> (true) or <code>f</code> is ternary (false)
 * @param hashAlg      a valid identifier for a <code>java.security.MessageDigest</code> instance such as <code>SHA-256</code>. The <code>MessageDigest</code> must support the <code>getDigestLength()</code> method.
 */
public NTRUEncryptionKeyGenerationParameters(int N, int q, int df, int dm0, int db, int c, int minCallsR, int minCallsMask, boolean hashSeed, byte[] oid, boolean sparse, boolean fastFp, Digest hashAlg)
{
    super(new SecureRandom(), db);
    this.N = N;
    this.q = q;
    this.df = df;
    this.db = db;
    this.dm0 = dm0;
    this.c = c;
    this.minCallsR = minCallsR;
    this.minCallsMask = minCallsMask;
    this.hashSeed = hashSeed;
    this.oid = oid;
    this.sparse = sparse;
    this.fastFp = fastFp;
    this.polyType = NTRUParameters.TERNARY_POLYNOMIAL_TYPE_SIMPLE;
    this.hashAlg = hashAlg;
    init();
}
 
Example 16
Project: ditb   File: TestEncryptionUtil.java   View source code 6 votes vote down vote up
@Test(expected = KeyException.class)
public void testWALKeyWrappingWithIncorrectKey() throws Exception {
  // set up the key provider for testing to resolve a key for our test subject
  Configuration conf = new Configuration(); // we don't need HBaseConfiguration for this
  conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());

  // generate a test key
  byte[] keyBytes = new byte[AES.KEY_LENGTH];
  new SecureRandom().nextBytes(keyBytes);
  String algorithm = conf.get(HConstants.CRYPTO_WAL_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
  Key key = new SecretKeySpec(keyBytes, algorithm);

  // wrap the test key
  byte[] wrappedKeyBytes = EncryptionUtil.wrapKey(conf, "hbase", key);
  assertNotNull(wrappedKeyBytes);

  // unwrap with an incorrect key
  EncryptionUtil.unwrapWALKey(conf, "other", wrappedKeyBytes);
}
 
Example 17
Project: TIIEHenry-Android-SDK   File: DESUtils.java   View source code 6 votes vote down vote up
/**
 * 加密
 * @param data
 * @param password
 * @return
 */
public static byte[] encrypt(byte[] data, String password) {
    try {
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        //创建一个密匙工厂,然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        //Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");
        //用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        //现在,获取数据并加密
        //正式执行加密操作
        return cipher.doFinal(data);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 18
Project: logistimo-web-service   File: SSLUtilities.java   View source code 6 votes vote down vote up
/**
 * Set the default X509 Trust Manager to an instance of a fake class that
 * trust all certificates, even the self-signed ones.
 */
private static void _trustAllHttpsCertificates() {
  SSLContext context;

  // Create a trust manager that does not validate certificate chains
  if (_trustManagers == null) {
    _trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
  } // if
  // Install the all-trusting trust manager:
  try {
    context = SSLContext.getInstance("SSL");
    context.init(null, _trustManagers, new SecureRandom());
  } catch (GeneralSecurityException gse) {
    throw new IllegalStateException(gse.getMessage());
  } // catch
  HttpsURLConnection.setDefaultSSLSocketFactory(context
      .getSocketFactory());
}
 
Example 19
Project: Hobbes-v1   File: Help.java   View source code 6 votes vote down vote up
private void sendCommandHelp(Input input, Output output) {
  SecureRandom r = new SecureRandom();
  Command command = CommandUtils.getCommand(input.getArgument(0));
  Message commandHelpEmbed = createEmbed(command.getSettings().getEmbedColor(),
      "Help: " + command.getSettings().getName(),
      "**Category:** `" + command.getSettings().getCategory() + "`\n**Usage:** `" + command
          .getSettings()
          .getHelp() + "`\n**Description:** `" + command
          .getSettings().getDescription() + "`");
  if (input.isFromType(ChannelType.TEXT)) {
    output.sendMessage("Sent you a DM. " + emojis[r.nextInt(emojis.length)]);
    output.sendPrivateMessage(commandHelpEmbed);
  } else {
    output.sendMessage(commandHelpEmbed);
  }
}
 
Example 20
Project: Hydrograph   File: GenerateUniqueJobIdUtil.java   View source code 6 votes vote down vote up
/**
 * Generates Unique Job Id.
 * 
 * @return {@link String}
 */
public String generateUniqueJobId() throws NoSuchAlgorithmException {
	String uniqueJobId = "";
	SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
	int number = 0;
	for (int i = 0; i < 20; i++) {
		number = random.nextInt(21);
	}
	byte[] secureRandom = random.getSeed(number);
	long milliSeconds = System.currentTimeMillis();
	String timeStampLong = Long.toString(milliSeconds);

	/*
	 * String timeStamp = new
	 * SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
	 * this.uniqueJobId=jobId.concat(""+secureRandom.hashCode()).concat(
	 * JOB_ID_STRING_SEPARATOR+timeStampLong) + JOB_ID_STRING_SEPARATOR +
	 * timeStamp;
	 */
	uniqueJobId = "Job_".concat("" + secureRandom.hashCode()).concat("_" + timeStampLong);

	return uniqueJobId;
}
 
Example 21
Project: wx-idk   File: HttpsRequestTools.java   View source code 6 votes vote down vote up
/**
   * 创建Http/Https请求对象
   * @author Rocye
   * @param url 请求地址
   * @param method 请求方式:GET/POST
   * @param certPath 证书路径
   * @param certPass 证书密码
* @param useCert 是否需要证书
   * @return Https连接
   * @throws Exception 任何异常
   * @version 2017.11.14
   */
  private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{
      URL realUrl = new URL(url);
      HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();

      //设置证书
if(useCert){
	KeyStore clientStore = KeyStore.getInstance("PKCS12");
	InputStream inputStream = new FileInputStream(certPath);
	clientStore.load(inputStream, certPass.toCharArray());
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(clientStore, certPass.toCharArray());
	KeyManager[] kms = kmf.getKeyManagers();
	SSLContext sslContext = SSLContext.getInstance("TLSv1");
	sslContext.init(kms, null, new SecureRandom());
	connection.setSSLSocketFactory(sslContext.getSocketFactory());
}

      // 设置通用的请求属性
      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setConnectTimeout(this.connectTimeout);
      connection.setReadTimeout(this.readTimeout);
      if("POST".equals(method)){
          // 发送POST请求必须设置如下两行
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setUseCaches(false);   // 忽略缓存
          connection.setRequestMethod("POST");
      }
      return connection;
  }
 
Example 22
Project: cas-5.1.0   File: CasOAuthConfiguration.java   View source code 6 votes vote down vote up
@PostConstruct
public void initializeServletApplicationContext() {
    final String oAuthCallbackUrl = casProperties.getServer().getPrefix() + BASE_OAUTH20_URL + '/' + CALLBACK_AUTHORIZE_URL_DEFINITION;

    final Service callbackService = this.webApplicationServiceFactory.createService(oAuthCallbackUrl);
    final RegisteredService svc = servicesManager.findServiceBy(callbackService);

    if (svc == null || !svc.getServiceId().equals(oAuthCallbackUrl)) {
        final RegexRegisteredService service = new RegexRegisteredService();
        service.setId(Math.abs(new SecureRandom().nextLong()));
        service.setEvaluationOrder(0);
        service.setName(service.getClass().getSimpleName());
        service.setDescription("OAuth Authentication Callback Request URL");
        service.setServiceId(oAuthCallbackUrl);
        service.setAttributeReleasePolicy(new DenyAllAttributeReleasePolicy());

        servicesManager.save(service);
        servicesManager.load();
    }
}
 
Example 23
Project: util4j   File: AesUtil.java   View source code 5 votes vote down vote up
/**
 * AES解密
 * @param encryptBytes 待解密的byte[]
 * @param decryptKey 解密密钥
 * @return 解密后的
 * @throws Exception
 */
public static byte[] AesDecryptByBytes(byte[] encryptBytes,byte[] decryptKey) throws Exception {
	KeyGenerator kgen = KeyGenerator.getInstance("AES");
	SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
	secureRandom.setSeed(decryptKey);
	kgen.init(128,secureRandom);
	Cipher cipher = Cipher.getInstance("AES");
	cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
	byte[] decryptBytes = cipher.doFinal(encryptBytes);
	return decryptBytes;
}
 
Example 24
Project: sstable-adaptor   File: UUIDGen.java   View source code 5 votes vote down vote up
private static long makeClockSeqAndNode()
{
    long clock = new SecureRandom().nextLong();

    long lsb = 0;
    lsb |= 0x8000000000000000L;                 // variant (2 bits)
    lsb |= (clock & 0x0000000000003FFFL) << 48; // clock sequence (14 bits)
    lsb |= makeNode();                          // 6 bytes
    return lsb;
}
 
Example 25
Project: ipack   File: CipherSpi.java   View source code 5 votes vote down vote up
protected void engineInit(
    int                 opmode,
    Key                 key,
    AlgorithmParameters params,
    SecureRandom        random) 
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    throw new InvalidAlgorithmParameterException("can't handle parameters in ElGamal");
}
 
Example 26
Project: xitk   File: IaikP11Slot.java   View source code 5 votes vote down vote up
private static byte[] generateKeyId(Session session) throws P11TokenException {
    SecureRandom random = new SecureRandom();
    byte[] keyId = null;
    do {
        keyId = new byte[8];
        random.nextBytes(keyId);
    }
    while (idExists(session, keyId));

    return keyId;
}
 
Example 27
Project: jdk8u-jdk   File: KerberosClientKeyExchange.java   View source code 5 votes vote down vote up
public void init(ProtocolVersion protocolVersion,
        ProtocolVersion clientVersion, SecureRandom rand,
        HandshakeInStream input, AccessControlContext acc,
        Object ServiceCreds) throws IOException {

    if (impl != null) {
        impl.init(protocolVersion, clientVersion,
                                rand, input, acc, ServiceCreds);
    }
}
 
Example 28
Project: esup-ecandidat   File: PasswordHashServicePBKDF2.java   View source code 5 votes vote down vote up
/**
 * Returns a salted PBKDF2 hash of the password.
 *
 * @param password
 *            the password to hash
 * @return a salted PBKDF2 hash of the password
 * @throws CustomException 
 */
public String createHash(char[] password) throws CustomException {
	try {
		// Generate a random salt
		SecureRandom random = new SecureRandom();
		byte[] salt = new byte[SALT_BYTE_SIZE];
		random.nextBytes(salt);

		// Hash the password
		byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
		return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
	}catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
		throw new CustomException(e);
	}
}
 
Example 29
Project: jdk8u-jdk   File: KerberosClientKeyExchange.java   View source code 5 votes vote down vote up
public KerberosClientKeyExchange(ProtocolVersion protocolVersion,
        ProtocolVersion clientVersion, SecureRandom rand,
        HandshakeInStream input, AccessControlContext acc,
        Object serverKeys) throws IOException {

    if (impl != null) {
        init(protocolVersion, clientVersion, rand, input, acc, serverKeys);
    } else {
        throw new IllegalStateException("Kerberos is unavailable");
    }
}
 
Example 30
Project: sentry   File: CustomPersistentRememberMeServices.java   View source code 5 votes vote down vote up
@Inject
public CustomPersistentRememberMeServices(JHipsterProperties jHipsterProperties, org.springframework.security.core.userdetails
    .UserDetailsService userDetailsService) {

    super(jHipsterProperties.getSecurity().getRememberMe().getKey(), userDetailsService);
    random = new SecureRandom();
}
 
Example 31
Project: ipack   File: SRP6Client.java   View source code 5 votes vote down vote up
/**
 * Initialises the client to begin new authentication attempt
 * @param N The safe prime associated with the client's verifier
 * @param g The group parameter associated with the client's verifier
 * @param digest The digest algorithm associated with the client's verifier
 * @param random For key generation
 */
public void init(BigInteger N, BigInteger g, Digest digest, SecureRandom random)
{
    this.N = N;
    this.g = g;
    this.digest = digest;
    this.random = random;
}
 
Example 32
Project: BiglyBT   File: JDKAlgorithmParameterGenerator.java   View source code 5 votes vote down vote up
@Override
     protected AlgorithmParameters engineGenerateParameters()
     {
         ElGamalParametersGenerator pGen = new ElGamalParametersGenerator();

if ( random != null )
{
	pGen.init(strength, 20, random);
}
else
{
	pGen.init(strength, 20, new SecureRandom());
}

         ElGamalParameters p = pGen.generateParameters();

         AlgorithmParameters params;

         try
         {
             params = AlgorithmParameters.getInstance("ElGamal", BouncyCastleProvider.PROVIDER_NAME);
             params.init(new ElGamalParameterSpec(p.getP(), p.getG()));
         }
         catch (Exception e)
         {
             throw new RuntimeException(e.getMessage());
         }

         return params;
     }
 
Example 33
Project: ipack   File: TlsBlockCipher.java   View source code 5 votes vote down vote up
protected int chooseExtraPadBlocks(SecureRandom r, int max)
{
    // return r.nextInt(max + 1);

    int x = r.nextInt();
    int n = lowestBitSet(x);
    return Math.min(n, max);
}
 
Example 34
Project: mi-firma-android   File: JseCryptoHelper.java   View source code 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public byte[] generateRandomBytes(final int numBytes) throws IOException {
    final SecureRandom sr;
    try {
        sr = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$
    }
    catch (final NoSuchAlgorithmException e) {
        throw new IOException("Algoritmo de generacion de aleatorios no valido: " + e, e); //$NON-NLS-1$
    }
    final byte[] randomBytes = new byte[numBytes];
    sr.nextBytes(randomBytes);
    return randomBytes;
}
 
Example 35
Project: smn-sdk-java   File: AesUtil.java   View source code 5 votes vote down vote up
/**
 * encrypt
 *
 * @param content  content to be encrpted
 * @param password encrypt password
 * @return String encrypted content
 */
public static String encrypt(String content, String password) {
    try {

        // create AES KeyGenerator
        KeyGenerator kgen = KeyGenerator.getInstance(SmnConstants.AES);

        // init 128 bit keygen utilizing password
        kgen.init(128, new SecureRandom(password.getBytes()));

        // gen secret key from password
        SecretKey secretKey = kgen.generateKey();

        // get basic encoding secret,unsupported throw exception
        byte[] enCodeFormat = secretKey.getEncoded();

        // transform to AES specialized secret key
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, SmnConstants.AES);

        // create cipher
        Cipher cipher = Cipher.getInstance(SmnConstants.AES);

        byte[] byteContent = content.getBytes(SmnConstants.DEFAULT_CHARSET);

        // init encrypt mode cipher
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] result = cipher.doFinal(byteContent);
        String encryptedStr = parseByte2HexStr(result);

        return encryptedStr;

    } catch (Exception e) {
        LOGGER.error("Aes encrypt failed.", e);
        throw new RuntimeException("Aes encrypt failed.", e);
    }

}
 
Example 36
Project: GitHub   File: EncryptUtils.java   View source code 5 votes vote down vote up
/**
 * DES加密模板
 *
 * @param data           数据
 * @param key            秘钥
 * @param algorithm      加密算法
 * @param transformation 转变
 * @param isEncrypt      {@code true}: 加密 {@code false}: 解密
 * @return 密文或者明文,适用于DES,3DES,AES
 */
public static byte[] desTemplate(final byte[] data, final byte[] key, final String algorithm, final String transformation, final boolean isEncrypt) {
    if (data == null || data.length == 0 || key == null || key.length == 0) return null;
    try {
        SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(transformation);
        SecureRandom random = new SecureRandom();
        cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, random);
        return cipher.doFinal(data);
    } catch (Throwable e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 37
Project: Cable-Android   File: Util.java   View source code 5 votes vote down vote up
public static <T> T getRandomElement(T[] elements) {
  try {
    return elements[SecureRandom.getInstance("SHA1PRNG").nextInt(elements.length)];
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 38
Project: PeSanKita-lib   File: PushServiceSocket.java   View source code 5 votes vote down vote up
public PushServiceSocket(SignalServiceUrl[] serviceUrls, CredentialsProvider credentialsProvider, String userAgent) {
  try {
    this.credentialsProvider         = credentialsProvider;
    this.userAgent                   = userAgent;
    this.signalConnectionInformation = new SignalConnectionInformation[serviceUrls.length];
    this.random                      = SecureRandom.getInstance("SHA1PRNG");

    for (int i = 0; i < serviceUrls.length; i++) {
      signalConnectionInformation[i] = new SignalConnectionInformation(serviceUrls[i]);
    }
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 39
Project: ipack   File: BaseWrapCipher.java   View source code 5 votes vote down vote up
protected void engineInit(
    int                 opmode,
    Key                 key,
    AlgorithmParameters params,
    SecureRandom        random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    AlgorithmParameterSpec  paramSpec = null;

    if (params != null)
    {
        for (int i = 0; i != availableSpecs.length; i++)
        {
            try
            {
                paramSpec = params.getParameterSpec(availableSpecs[i]);
                break;
            }
            catch (Exception e)
            {
                // try next spec
            }
        }

        if (paramSpec == null)
        {
            throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
        }
    }

    engineParams = params;
    engineInit(opmode, key, paramSpec, random);
}
 
Example 40
Project: hadoop-oss   File: KeyStoreTestUtil.java   View source code 5 votes vote down vote up
@SuppressWarnings("deprecation")
/**
 * Create a self-signed X.509 Certificate.
 *
 * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
    throws CertificateEncodingException,
           InvalidKeyException,
           IllegalStateException,
           NoSuchProviderException, NoSuchAlgorithmException, SignatureException{

  Date from = new Date();
  Date to = new Date(from.getTime() + days * 86400000l);
  BigInteger sn = new BigInteger(64, new SecureRandom());
  KeyPair keyPair = pair;
  X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
  X500Principal  dnName = new X500Principal(dn);

  certGen.setSerialNumber(sn);
  certGen.setIssuerDN(dnName);
  certGen.setNotBefore(from);
  certGen.setNotAfter(to);
  certGen.setSubjectDN(dnName);
  certGen.setPublicKey(keyPair.getPublic());
  certGen.setSignatureAlgorithm(algorithm);

  X509Certificate cert = certGen.generate(pair.getPrivate());
  return cert;
}