Java Code Examples for java.security.SecureRandom

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project b1-pack, under directory /standard/src/main/java/org/b1/pack/standard/common/.

Source file: Volumes.java

  20 
vote

public static byte[] generateRandomBytes(int count){
  SecureRandom random=secureRandom;
  if (random == null) {
    random=secureRandom=new SecureRandom();
  }
  byte[] buffer=new byte[count];
  random.nextBytes(buffer);
  return buffer;
}
 

Example 2

From project BF3-Battlelog, under directory /src/net/sf/andhsli/hotspotlogin/.

Source file: SimpleCrypto.java

  20 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 3

From project ajah, under directory /ajah-crypto/src/main/java/com/ajah/crypto/.

Source file: Crypto.java

  18 
vote

private static void keyGen(){
  final SecureRandom sr=new SecureRandom();
  final byte[] keyBytes=new byte[128];
  sr.nextBytes(keyBytes);
  final Scanner scanner=new Scanner(System.in);
  System.out.print("Algorithm: [HmacSHA1] ");
  final String algorithm=scanner.nextLine();
  if (StringUtils.isBlank(algorithm) || algorithm.equals("HmacSHA1")) {
    System.out.print("Secret: ");
    final String secret=scanner.nextLine();
    System.out.print(getHmacSha1Hex(secret));
  }
}
 

Example 4

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/auth/.

Source file: DigestScheme.java

  18 
vote

/** 
 * Creates a random cnonce value based on the current time.
 * @return The cnonce value as String.
 */
public static String createCnonce(){
  SecureRandom rnd=new SecureRandom();
  byte[] tmp=new byte[8];
  rnd.nextBytes(tmp);
  return encode(tmp);
}
 

Example 5

From project android-bankdroid, under directory /src/net/sf/andhsli/hotspotlogin/.

Source file: SimpleCrypto.java

  18 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 6

From project android_8, under directory /src/com/defuzeme/communication/.

Source file: Send.java

  18 
vote

private String generateToken(){
  SecureRandom random=null;
  String token=null;
  if ((token=DefuzeMe.Preferences.get(string.authToken)) == null) {
    random=new SecureRandom();
    token=new BigInteger(130,random).toString(32).substring(0,16);
    DefuzeMe.Preferences.save(string.authToken,token);
  }
  return token;
}
 

Example 7

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/spok/.

Source file: GenerateId.java

  18 
vote

/** 
 * Generates a unique identifier by generating a random number and getting its digest
 * @return the new SpectrumID
 */
public static String generateId(){
  try {
    SecureRandom prng=SecureRandom.getInstance("SHA1PRNG");
    String randomNum=new Integer(prng.nextInt()).toString();
    MessageDigest sha=MessageDigest.getInstance("SHA-1");
    byte[] result=sha.digest(randomNum.getBytes());
    spectrumID=hexEncode(result);
    spectrumID="sid_" + spectrumID;
  }
 catch (  NoSuchAlgorithmException ex) {
    System.err.println(ex);
  }
  return spectrumID;
}
 

Example 8

From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/.

Source file: PasswordEncoder.java

  18 
vote

public final String encode(String password){
  try {
    byte[] saltBytes=new byte[44];
    SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
    random.nextBytes(saltBytes);
    String salt=bytesToHexString(saltBytes);
    String hash=hash(password,salt);
    return salt.substring(0,44) + hash + salt.substring(44,88);
  }
 catch (  Exception e) {
    throw new NestableRuntimeException(e);
  }
}
 

Example 9

From project cas, under directory /cas-server-extension-clearpass/src/main/java/org/jasig/cas/extension/clearpass/.

Source file: EncryptedMapDecorator.java

  18 
vote

private static String getRandomSalt(final int size){
  final SecureRandom secureRandom=new SecureRandom();
  final byte[] bytes=new byte[size];
  secureRandom.nextBytes(bytes);
  return getFormattedText(bytes);
}
 

Example 10

From project chililog-server, under directory /src/main/java/org/chililog/server/common/.

Source file: CryptoUtils.java

  18 
vote

/** 
 * <p> From a password, a number of iterations and a salt, returns the corresponding hash. For convenience, the salt is stored within the hash. </p> <p> This convention is used: <code>base64(hash(plainTextValue + salt)+salt)</code> </p>
 * @param plainTextValue String The password to encrypt
 * @param salt byte[] The salt. If null, one will be created on your behalf.
 * @return String The hash password
 * @throws ChiliLogException if SHA-512 is not supported or UTF-8 is not a supported encoding algorithm
 */
public static String createSHA512Hash(String plainTextValue,byte[] salt) throws ChiliLogException {
  try {
    SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
    salt=new byte[8];
    random.nextBytes(salt);
    return createSHA512Hash(plainTextValue,salt,true);
  }
 catch (  Exception ex) {
    throw new ChiliLogException(ex,"Error attempting to hash passwords. " + ex.getMessage());
  }
}
 

Example 11

From project connectbot, under directory /src/com/trilead/ssh2/.

Source file: Connection.java

  18 
vote

/** 
 * Send an SSH_MSG_IGNORE packet. This method will generate a random data attribute (length between 0 (invlusive) and 16 (exclusive) bytes, contents are random bytes). <p> This method must only be called once the connection is established.
 * @throws IOException
 */
public synchronized void sendIgnorePacket() throws IOException {
  SecureRandom rnd=getOrCreateSecureRND();
  byte[] data=new byte[rnd.nextInt(16)];
  rnd.nextBytes(data);
  sendIgnorePacket(data);
}
 

Example 12

From project droidparts, under directory /extra/src/org/droidparts/util/crypto/.

Source file: Crypter.java

  18 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 13

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/model/.

Source file: DbObject.java

  18 
vote

private static int colorFor(Long hash){
  float[] baseHues=Feed.getBaseHues();
  ByteBuffer bos=ByteBuffer.allocate(8);
  bos.putLong(hash);
  byte[] hashBytes=new byte[8];
  bos.position(0);
  bos.get(hashBytes);
  SecureRandom r=new SecureRandom(hashBytes);
  float hsv[]=new float[]{baseHues[r.nextInt(baseHues.length)],r.nextFloat(),r.nextFloat()};
  hsv[0]=hsv[0] + 20 * r.nextFloat() - 10;
  hsv[1]=hsv[1] * 0.2f + 0.8f;
  hsv[2]=hsv[2] * 0.2f + 0.8f;
  return Color.HSVToColor(hsv);
}
 

Example 14

From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/internal/.

Source file: SecureProperties.java

  18 
vote

public static String generateRandomKey(int bits) throws GeneralSecurityException {
  SecureRandom rnd=new SecureRandom();
  byte[] result=new byte[bits / 8];
  rnd.nextBytes(result);
  return Util.toBase16(result);
}
 

Example 15

From project egov-data, under directory /easyCompany2/src/main/java/egovframework/rte/tex/com/service/.

Source file: EgovNumberUtil.java

  18 
vote

public static int getRandomNum(int startNum,int endNum){
  int randomNum=0;
  try {
    SecureRandom rnd=new SecureRandom();
    do {
      randomNum=rnd.nextInt(endNum + 1);
    }
 while (randomNum < startNum);
  }
 catch (  Exception e) {
    log.trace(e.getMessage());
  }
  return randomNum;
}
 

Example 16

From project encfs-java, under directory /src/main/java/org/mrpdaemon/sec/encfs/.

Source file: EncFSCrypto.java

  18 
vote

/** 
 * Encodes the given volume key using the supplied password parameters, placing it into the EncFSConfig
 * @param config Partially initialized volume configuration
 * @param password Password to use for encoding the key
 * @param volKey Volume key to encode
 * @throws EncFSInvalidConfigException Corrupt data in config file
 * @throws EncFSCorruptDataException Corrupt data in config file
 * @throws EncFSUnsupportedException Stream cipher mode unsupported in current runtime
 */
public static void encodeVolumeKey(EncFSConfig config,String password,byte[] volKey) throws EncFSInvalidConfigException, EncFSUnsupportedException, EncFSCorruptDataException {
  SecureRandom random=new SecureRandom();
  config.setSaltLength(20);
  byte[] salt=new byte[20];
  random.nextBytes(salt);
  config.setSaltStr(EncFSBase64.encodeBytes(salt));
  byte[] pbkdf2Data=derivePasswordKey(config,password);
  byte[] encodedVolKey=encryptVolumeKey(config,pbkdf2Data,volKey);
  config.setEncodedKeyLength(encodedVolKey.length);
  config.setEncodedKeyStr(EncFSBase64.encodeBytes(encodedVolKey));
}
 

Example 17

From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/util/.

Source file: ServerPortGenerator.java

  18 
vote

/** 
 * Super simple no-collision-detection method of grabbing a port. We use a large enough pool in hopes that our odds of a collision are low
 * @return
 */
public int generatePort(){
  SecureRandom random=new SecureRandom();
  int port=random.nextInt(10000);
  port+=40000;
  System.err.println("Server Port:" + port);
  return port;
}
 

Example 18

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/encryption/.

Source file: AESCTRNoPaddingProvider.java

  18 
vote

@Override public AESCTRNoPaddingEncryptor build(){
  ByteBuffer buffer=ByteBuffer.allocate(16);
  byte[] seed=new byte[12];
  SecureRandom random=new SecureRandom();
  random.nextBytes(seed);
  buffer.put(seed).putInt(1);
  return new AESCTRNoPaddingEncryptor(key,buffer.array());
}
 

Example 19

From project Gibberbot, under directory /src/net/java/otr4j/crypto/.

Source file: SM.java

  18 
vote

/** 
 * Generate a random exponent 
 */
public static BigInteger randomExponent(){
  SecureRandom sr=new SecureRandom();
  byte[] sb=new byte[MOD_LEN_BYTES];
  sr.nextBytes(sb);
  return new BigInteger(1,sb);
}
 

Example 20

From project httpcache4j, under directory /httpcache4j-api/src/main/java/org/codehaus/httpcache4j/util/.

Source file: SecureRandomFactory.java

  18 
vote

public static SecureRandom getRandom(byte[] seed){
  try {
    SecureRandom rnd=SecureRandom.getInstance("SHA1PRNG");
    if (seed != null) {
      rnd.setSeed(seed);
    }
    return rnd;
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 21

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/impl/auth/.

Source file: DigestScheme.java

  18 
vote

/** 
 * Creates a random cnonce value based on the current time.
 * @return The cnonce value as String.
 */
public static String createCnonce(){
  SecureRandom rnd=new SecureRandom();
  byte[] tmp=new byte[8];
  rnd.nextBytes(tmp);
  return encode(tmp);
}
 

Example 22

From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.

Source file: CACertManager.java

  18 
vote

public KeyPair generateKeyPair(String algo,String algo2,int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
  KeyPairGenerator keyGen=KeyPairGenerator.getInstance(algo);
  SecureRandom random=SecureRandom.getInstance(algo2);
  keyGen.initialize(keySize,random);
  KeyPair kp=keyGen.generateKeyPair();
  return kp;
}
 

Example 23

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/oak/security/authentication/token/.

Source file: TokenProviderImpl.java

  18 
vote

@Nonnull private static String generateKey(int size){
  SecureRandom random=new SecureRandom();
  byte key[]=new byte[size];
  random.nextBytes(key);
  StringBuilder res=new StringBuilder(key.length * 2);
  for (  byte b : key) {
    res.append(Text.hexTable[(b >> 4) & 15]);
    res.append(Text.hexTable[b & 15]);
  }
  return res.toString();
}
 

Example 24

From project jDcHub, under directory /jdchub-webadmin/src/main/java/ru/sincore/beans/rest/utils/.

Source file: Session.java

  18 
vote

/** 
 * Main constructor. Generate unique token on creation
 */
public Session(){
  try {
    SecureRandom secureRandom=SecureRandom.getInstance("SHA1PRNG");
    String randomNumber=new Integer(secureRandom.nextInt()).toString();
    MessageDigest messageDigest=MessageDigest.getInstance("SHA-1");
    byte[] result=messageDigest.digest(randomNumber.getBytes());
    token=hexEncode(result);
  }
 catch (  NoSuchAlgorithmException e) {
    token=UUID.randomUUID().toString();
  }
  lastAccess=new Date();
}
 

Example 25

From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/.

Source file: OpenSSLKey.java

  18 
vote

private IvParameterSpec generateIV(){
  byte[] b=new byte[this.ivLength];
  SecureRandom sr=new SecureRandom();
  sr.nextBytes(b);
  return new IvParameterSpec(b);
}
 

Example 26

From project JMaNGOS, under directory /Realm/src/main/java/org/jmangos/realm/network/packet/wow/server/.

Source file: SMSG_AUTH_CHALLENGE.java

  18 
vote

@Override protected void writeImpl(){
  final RealmToClientChannelHandler channelHandler=(RealmToClientChannelHandler)getChannel().getChannel().getPipeline().getLast();
  final SecureRandom random=new SecureRandom();
  final byte[] seed=random.generateSeed(4);
  channelHandler.setSeed(seed);
  writeD(1);
  writeB(seed);
  writeB(random.generateSeed(16));
  writeB(random.generateSeed(16));
}
 

Example 27

From project lorsource, under directory /src/main/java/ru/org/linux/csrf/.

Source file: CSRFProtectionService.java

  18 
vote

public static void generateCSRFCookie(HttpServletRequest request,HttpServletResponse response){
  SecureRandom random=new SecureRandom();
  byte[] value=new byte[16];
  random.nextBytes(value);
  String token=new String(Base64.encodeBase64(value));
  Cookie cookie=new Cookie(CSRF_COOKIE,token);
  cookie.setMaxAge(TWO_YEARS);
  cookie.setPath("/");
  response.addCookie(cookie);
  request.setAttribute(CSRF_ATTRIBUTE,token);
}
 

Example 28

From project Monetizing-Android-Demo-Project, under directory /src/dk/trifork/geeknight/bigredbutton/.

Source file: SimpleCrypto.java

  18 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 29

From project netifera, under directory /platform/com.netifera.platform.net.ssh/com.netifera.platform.net.ssh/src/com/trilead/ssh2/.

Source file: Connection.java

  18 
vote

/** 
 * Send an SSH_MSG_IGNORE packet. This method will generate a random data attribute (length between 0 (invlusive) and 16 (exclusive) bytes, contents are random bytes). <p> This method must only be called once the connection is established.
 * @throws IOException
 */
public synchronized void sendIgnorePacket() throws IOException {
  SecureRandom rnd=getOrCreateSecureRND();
  byte[] data=new byte[rnd.nextInt(16)];
  rnd.nextBytes(data);
  sendIgnorePacket(data);
}
 

Example 30

From project org.openscada.atlantis, under directory /org.openscada.core.net/src/org/openscada/core/net/.

Source file: ConnectionHelper.java

  18 
vote

private static SecureRandom getRandom(final ConnectionInformation connectionInformation) throws NoSuchAlgorithmException {
  final String sslRandom=connectionInformation.getProperties().get("sslRandom");
  SecureRandom random=null;
  if (sslRandom != null && sslRandom.length() > 0) {
    random=SecureRandom.getInstance(sslRandom);
    return random;
  }
  return null;
}
 

Example 31

From project Pitbull, under directory /pitbull-core/src/main/java/org/jboss/pitbull/internal/nio/websocket/impl/oio/internal/util/.

Source file: Hash.java

  18 
vote

private static SecureRandom createRandom(){
  try {
    SecureRandom random=SecureRandom.getInstance(secureRandomAlgorithm);
    random.setSeed(SecureRandom.getInstance(secureRandomAlgorithm).generateSeed(64));
    return random;
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("runtime does not support secure random algorithm: " + secureRandomAlgorithm);
  }
}
 

Example 32

From project QuotaForAndroid, under directory /Quota/src/com/southfreo/quota/utils/.

Source file: Security.java

  18 
vote

private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
  kgen.init(128,sr);
  SecretKey skey=kgen.generateKey();
  byte[] raw=skey.getEncoded();
  return raw;
}
 

Example 33

From project safe, under directory /Safe/src/org/openintents/safe/.

Source file: CryptoHelper.java

  18 
vote

/** 
 * Generate a random salt for use with the cipher.
 * @author Randy McEoin
 * @return String version of the 8 byte salt
 */
public static String generateSalt() throws NoSuchAlgorithmException {
  byte[] salt=new byte[8];
  SecureRandom sr;
  try {
    sr=SecureRandom.getInstance("SHA1PRNG");
    sr.nextBytes(salt);
    if (debug)     Log.d(TAG,"generateSalt: salt=" + salt.toString());
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
    throw e;
  }
  return toHexString(salt);
}
 

Example 34

From project Sage-Mobile-Calc, under directory /src/com/trilead/ssh2/.

Source file: Connection.java

  18 
vote

/** 
 * Send an SSH_MSG_IGNORE packet. This method will generate a random data attribute (length between 0 (invlusive) and 16 (exclusive) bytes, contents are random bytes). <p> This method must only be called once the connection is established.
 * @throws IOException
 */
public synchronized void sendIgnorePacket() throws IOException {
  SecureRandom rnd=getOrCreateSecureRND();
  byte[] data=new byte[rnd.nextInt(16)];
  rnd.nextBytes(data);
  sendIgnorePacket(data);
}
 

Example 35

From project android-client_1, under directory /src/com/googlecode/asmack/dns/.

Source file: Client.java

  17 
vote

/** 
 * Create a new DNS client.
 */
public Client(){
  try {
    random=SecureRandom.getInstance("SHA1PRNG");
  }
 catch (  NoSuchAlgorithmException e1) {
    random=new SecureRandom();
  }
}
 

Example 36

From project apg, under directory /src/org/thialfihar/android/apg/.

Source file: Apg.java

  17 
vote

public static String generateRandomString(int length){
  SecureRandom random=new SecureRandom();
  byte bytes[]=new byte[length];
  random.nextBytes(bytes);
  String result="";
  for (int i=0; i < length; ++i) {
    int v=(bytes[i] + 256) % 64;
    if (v < 10) {
      result+=(char)('0' + v);
    }
 else     if (v < 36) {
      result+=(char)('A' + v - 10);
    }
 else     if (v < 62) {
      result+=(char)('a' + v - 36);
    }
 else     if (v == 62) {
      result+='_';
    }
 else     if (v == 63) {
      result+='.';
    }
  }
  return result;
}
 

Example 37

From project ardverk-commons, under directory /src/main/java/org/ardverk/security/.

Source file: SecurityUtils.java

  17 
vote

/** 
 * Creates and returns a  {@link SecureRandom}. The difference between this factory method and  {@link SecureRandom}'s default constructor is that this will try to initialize the  {@link SecureRandom} withan initial seed from /dev/urandom while the default constructor will attempt to do the same from /dev/random which may block if there is not enough data available.
 */
public static SecureRandom createSecureRandom(){
  File file=new File("/dev/urandom");
  if (file.exists() && file.canRead()) {
    try (DataInputStream in=new DataInputStream(new FileInputStream(file))){
      byte[] seed=new byte[SEED_LENGTH];
      in.readFully(seed);
      return new SecureRandom(seed);
    }
 catch (    SecurityException|IOException ignore) {
    }
  }
  return new SecureRandom();
}
 

Example 38

From project AsmackService, under directory /src/com/googlecode/asmack/dns/.

Source file: Client.java

  17 
vote

/** 
 * Create a new DNS client.
 */
public Client(){
  try {
    random=SecureRandom.getInstance("SHA1PRNG");
  }
 catch (  NoSuchAlgorithmException e1) {
    random=new SecureRandom();
  }
}
 

Example 39

From project AuthDB, under directory /src/main/java/com/authdb/scripts/cms/.

Source file: Joomla.java

  17 
vote

public static String hash(String username,String passwd){
  StringBuffer saltBuf=new StringBuffer();
  if (_rnd == null)   _rnd=new SecureRandom();
{
    int i;
    for (i=0; i < 32; i++) {
      saltBuf.append(Integer.toString(_rnd.nextInt(36),36));
    }
    String salt=saltBuf.toString();
    return Encryption.md5(passwd + salt) + ":" + salt;
  }
}
 

Example 40

From project BazaarUtils, under directory /src/org/alexd/jsonrpc/.

Source file: JSONRPCEncryptedHttpClient.java

  17 
vote

/** 
 * Construct a JSONRPCClient from a given uri, for calling encrypted methods
 * @param uri The URI of the JSON-RPC service
 * @param pKey PublicKey of the server
 * @param prefs The preferences which will contain the session_key
 */
public JSONRPCEncryptedHttpClient(String uri,PublicKey pKey,SharedPreferences prefs) throws GeneralSecurityException {
  super(uri);
  setConnectionTimeout(30000);
  setSoTimeout(60000);
  this.publicKey=pKey;
  rsa=Cipher.getInstance("RSA/None/OAEPPADDING");
  kgen=KeyGenerator.getInstance("AES");
  SecureRandom sr=new SecureRandom();
  byte[] ivBytes=sr.generateSeed(16);
  ips=new IvParameterSpec(ivBytes);
  rsa.init(Cipher.ENCRYPT_MODE,publicKey);
  iv=Base64.encode(rsa.doFinal(ivBytes));
  signature=Signature.getInstance("SHA1withRSA");
  this.preferences=prefs;
  if (this.preferences != null) {
    sessionKey=preferences.getString(PREF_SESSION_KEY,null);
  }
}
 

Example 41

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: CertificateGenerator.java

  17 
vote

public KeyPair generateKeyPair(){
  try {
    KeyPairGenerator generator=KeyPairGenerator.getInstance("RSA","BC");
    generator.initialize(KEY_SIZE,new SecureRandom());
    return generator.generateKeyPair();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("Cannot generate RSA key pair",e);
  }
catch (  NoSuchProviderException e) {
    throw new RuntimeException("Cannot generate RSA key pair",e);
  }
}
 

Example 42

From project cometd, under directory /cometd-java/cometd-java-oort/src/main/java/org/cometd/oort/.

Source file: Oort.java

  17 
vote

public Oort(BayeuxServer bayeux,String url){
  _bayeux=bayeux;
  _url=url;
  _id=UUID.randomUUID().toString();
  _logger=LoggerFactory.getLogger(getClass().getName() + "." + _url);
  _debug=String.valueOf(BayeuxServerImpl.DEBUG_LOG_LEVEL).equals(bayeux.getOption(BayeuxServerImpl.LOG_LEVEL));
  _oortSession=bayeux.newLocalSession("oort");
  _secret=Long.toHexString(new SecureRandom().nextLong());
}
 

Example 43

From project commons-j, under directory /src/test/java/nerds/antelax/commons/net/pubsub/.

Source file: MessageMarshalling.java

  17 
vote

private static ApplicationMessage newApplication(){
  final byte[] data=new byte[new SecureRandom().nextInt(2048)];
  for (int pos=0; pos < data.length; ++pos)   data[pos]=(byte)(pos % Byte.MAX_VALUE);
  final ApplicationMessage rv=new ApplicationMessage(data,"topic-" + System.currentTimeMillis());
  rv.sourceID(UUID.randomUUID());
  rv.serverID(UUID.randomUUID());
  return rv;
}
 

Example 44

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityApplic.java

  17 
vote

public static SecretKey keyExchange(ObjectInputStream in,ObjectOutputStream out) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IOException, ClassNotFoundException, NoSuchPaddingException {
  KeyPairGenerator gen=KeyPairGenerator.getInstance("RSA");
  gen.initialize(1024,new SecureRandom());
  KeyPair keys=gen.generateKeyPair();
  PublicKey publicKey=keys.getPublic();
  PrivateKey privateKey=keys.getPrivate();
  out.writeObject(new KeyExchangeClient(publicKey));
  out.flush();
  KeyExchangeServer response=(KeyExchangeServer)in.readObject();
  Cipher decryptor=Cipher.getInstance("RSA/ECB/PKCS1Padding");
  decryptor.init(Cipher.DECRYPT_MODE,privateKey);
  byte[] sessionKeyEncoded=decryptor.doFinal(response.getCryptedSessionKey());
  return new SecretKeySpec(sessionKeyEncoded,"DES");
}
 

Example 45

From project CraftCommons, under directory /src/main/java/com/craftfire/commons/encryption/.

Source file: PHPass.java

  17 
vote

public PHPass(int iteration_count_log2){
  if (iteration_count_log2 < 4 || iteration_count_log2 > 31) {
    iteration_count_log2=8;
  }
  this.iteration_count_log2=iteration_count_log2;
  this.random_gen=new SecureRandom();
}
 

Example 46

From project eucalyptus, under directory /clc/modules/core/src/edu/ucsb/eucalyptus/keys/.

Source file: KeyTool.java

  17 
vote

public KeyPair getKeyPair(){
  KeyPairGenerator keyGen=null;
  try {
    keyGen=KeyPairGenerator.getInstance(this.keyAlgorithm);
    SecureRandom random=new SecureRandom();
    random.setSeed(System.currentTimeMillis());
    keyGen.initialize(this.keySize,random);
    KeyPair keyPair=keyGen.generateKeyPair();
    return keyPair;
  }
 catch (  Exception e) {
    System.exit(1);
    return null;
  }
}
 

Example 47

From project g414-hash, under directory /src/test/java/com/g414/hash/bloom/.

Source file: BloomFilterTestBase.java

  17 
vote

public void doTestLongBloomFilter_Randomized(BloomTestConfig[] configs) throws NoSuchAlgorithmException {
  for (  BloomTestConfig config : configs) {
    LongHash hash=this.getHash();
    System.out.println("long bloom test randomized config (" + hash.getName() + ") : "+ config);
    BloomFilter filter=new BloomFilter(hash,config.maxSize,config.bitsPerItem);
    SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(config.seed);
    for (int i=0; i < config.maxSize; i++) {
      filter.put("test__" + (Math.abs(random.nextLong()) % config.MAX_DOMAIN));
    }
    int pos=0;
    for (int i=0; i < config.MAX_DOMAIN; i++) {
      if (filter.contains("test__" + Integer.toString(i))) {
        pos+=1;
      }
    }
    int falsePos=pos - config.maxSize;
    int projectedErrors=(int)Math.ceil(config.MAX_DOMAIN * Math.pow(0.62,config.bitsPerItem));
    System.out.println("long bloom test randomized result : " + falsePos + "  "+ projectedErrors);
    Assert.assertTrue(falsePos * 0.95 <= 10 + Math.ceil(config.MAX_DOMAIN * Math.pow(0.62,config.bitsPerItem)));
  }
}
 

Example 48

From project gatein-common, under directory /common/src/main/java/org/gatein/common/util/.

Source file: UUIDGenerator.java

  17 
vote

public UUIDGenerator(){
  try {
    StringBuffer buffer=new StringBuffer(16);
    byte[] addr=InetAddress.getLocalHost().getAddress();
    buffer.append(toHex(toInt(addr),8));
    buffer.append(toHex(System.identityHashCode(this),8));
    midValue=buffer.toString();
    seeder=new SecureRandom();
    seeder.nextInt();
  }
 catch (  Exception e) {
    throw new Error("Not possible");
  }
}
 

Example 49

From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.

Source file: HttpUtils.java

  17 
vote

/** 
 * Open an URL connection. If HTTPS, accepts any certificate even if not valid, and connects to any host name.
 * @param url The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static URLConnection getConnection(URL url) throws IOException, NoSuchAlgorithmException, KeyManagementException {
  URLConnection conn=url.openConnection();
  if (conn instanceof HttpsURLConnection) {
    SSLContext context=SSLContext.getInstance("TLS");
    context.init(new KeyManager[0],TRUST_MANAGER,new SecureRandom());
    SSLSocketFactory socketFactory=context.getSocketFactory();
    ((HttpsURLConnection)conn).setSSLSocketFactory(socketFactory);
    ((HttpsURLConnection)conn).setHostnameVerifier(HOSTNAME_VERIFIER);
  }
  conn.setConnectTimeout(SOCKET_TIMEOUT);
  conn.setReadTimeout(SOCKET_TIMEOUT);
  return conn;
}
 

Example 50

From project hdiv, under directory /hdiv-core/src/main/java/org/hdiv/cipher/.

Source file: KeyFactory.java

  17 
vote

/** 
 * This method is called whenever a key needs to be generated.
 * @return Key the encryption key
 */
public Key generateKey(){
  try {
    SecureRandom random=SecureRandom.getInstance(this.prngAlgorithm,this.provider);
    byte[] iv=new byte[16];
    random.nextBytes(iv);
    KeyGenerator kgen=KeyGenerator.getInstance(algorithm);
    kgen.init(keySize,random);
    SecretKey skey=kgen.generateKey();
    byte[] raw=skey.getEncoded();
    SecretKeySpec skeySpec=new SecretKeySpec(raw,algorithm);
    Key key=new Key();
    key.setKey(skeySpec);
    key.setInitVector(iv);
    return key;
  }
 catch (  Exception e) {
    String errorMessage=HDIVUtil.getMessage("key.factory.generate",e.getMessage());
    throw new HDIVException(errorMessage,e);
  }
}
 

Example 51

From project http-testing-harness, under directory /server-provider/src/test/java/org/sonatype/tests/http/server/jetty/behaviour/.

Source file: BehaviourSuiteConfiguration.java

  17 
vote

private static void trustAllHttpsCertificates(){
  SSLContext context;
  TrustManager[] _trustManagers=new TrustManager[]{new CustomTrustManager()};
  try {
    context=SSLContext.getInstance("SSL");
    context.init(null,_trustManagers,new SecureRandom());
  }
 catch (  GeneralSecurityException gse) {
    throw new IllegalStateException(gse.getMessage());
  }
  HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
 

Example 52

From project james-mime4j, under directory /dom/src/test/java/org/apache/james/mime4j/message/.

Source file: StringInputStreamTest.java

  17 
vote

private static void bufferedReadTest(final String testString) throws IOException {
  SecureRandom rnd=new SecureRandom();
  byte[] expected=testString.getBytes(CharsetUtil.UTF_8.name());
  InputStream in=new StringInputStream(testString,CharsetUtil.UTF_8);
  byte[] buffer=new byte[128];
  int offset=0;
  while (true) {
    int bufferOffset=rnd.nextInt(64);
    int bufferLength=rnd.nextInt(64);
    int read=in.read(buffer,bufferOffset,bufferLength);
    if (read == -1) {
      assertEquals(offset,expected.length);
      break;
    }
 else {
      assertTrue(read <= bufferLength);
      while (read > 0) {
        assertTrue(offset < expected.length);
        assertEquals(expected[offset],buffer[bufferOffset]);
        offset++;
        bufferOffset++;
        read--;
      }
    }
  }
}
 

Example 53

From project jboss-sasl, under directory /src/main/java/org/jboss/sasl/localuser/.

Source file: LocalUserServer.java

  17 
vote

private Random getRandom(){
  if (useSecureRandom) {
    return new SecureRandom();
  }
 else {
    return new Random();
  }
}
 

Example 54

From project k-9, under directory /src/com/fsck/k9/mail/transport/.

Source file: TrustedSocketFactory.java

  17 
vote

public TrustedSocketFactory(String host,boolean secure) throws NoSuchAlgorithmException, KeyManagementException {
  SSLContext sslContext=SSLContext.getInstance("TLS");
  sslContext.init(null,new TrustManager[]{TrustManagerFactory.get(host,secure)},new SecureRandom());
  mSocketFactory=sslContext.getSocketFactory();
  mSchemeSocketFactory=org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
  mSchemeSocketFactory.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
 

Example 55

From project maven-shared, under directory /maven-shared-utils/src/main/java/org/apache/maven/shared/utils/io/.

Source file: FileUtils.java

  17 
vote

/** 
 * Create a temporary file in a given directory. <p/> <p>The file denoted by the returned abstract pathname did not exist before this method was invoked, any subsequent invocation of this method will yield a different file name.</p> <p/> The filename is prefixNNNNNsuffix where NNNN is a random number </p> <p>This method is different to  {@link File#createTempFile(String,String,File)} of JDK 1.2as it doesn't create the file itself. It uses the location pointed to by java.io.tmpdir when the parentDir attribute is null.</p> <p>To delete automatically the file created by this method, use the {@link File#deleteOnExit()} method.</p>
 * @param prefix    prefix before the random number
 * @param suffix    file extension; include the '.'
 * @param parentDir Directory to create the temporary file in <code>-java.io.tmpdir</code>used if not specificed
 * @return a File reference to the new temporary file.
 */
public static File createTempFile(@Nonnull String prefix,@Nonnull String suffix,@Nullable File parentDir){
  File result;
  String parent=System.getProperty("java.io.tmpdir");
  if (parentDir != null) {
    parent=parentDir.getPath();
  }
  DecimalFormat fmt=new DecimalFormat("#####");
  SecureRandom secureRandom=new SecureRandom();
  long secureInitializer=secureRandom.nextLong();
  Random rand=new Random(secureInitializer + Runtime.getRuntime().freeMemory());
  do {
    result=new File(parent,prefix + fmt.format(Math.abs(rand.nextInt())) + suffix);
  }
 while (result.exists());
  return result;
}
 

Example 56

From project nuxeo-services, under directory /nuxeo-platform-directory/nuxeo-platform-directory-ldap/src/main/java/org/nuxeo/ecm/directory/ldap/.

Source file: LDAPDirectory.java

  17 
vote

/** 
 * Create a new SSLSocketFactory that creates a Socket regardless of the certificate used.
 * @throws SSLException if initialization fails.
 */
public TrustingSSLSocketFactory(){
  try {
    SSLContext sslContext=SSLContext.getInstance("TLS");
    sslContext.init(null,new TrustManager[]{new TrustingX509TrustManager()},new SecureRandom());
    factory=sslContext.getSocketFactory();
  }
 catch (  NoSuchAlgorithmException nsae) {
    throw new RuntimeException("Unable to initialize the SSL context:  ",nsae);
  }
catch (  KeyManagementException kme) {
    throw new RuntimeException("Unable to register a trust manager:  ",kme);
  }
}
 

Example 57

From project Ohmage_Phone, under directory /src/edu/ucla/cens/pdc/libpdc/util/.

Source file: EncryptionHelper.java

  17 
vote

public static byte[] encryptAsymData(PublicKey public_key,byte[] data) throws PDCEncryptionException {
  BSONEncoder encoder=new BSONEncoder();
  DBObject obj=new BasicDBList();
  SecureRandom random=new SecureRandom();
  KeyGenerator kg;
  Cipher cipher;
  SecretKey secret_key;
  byte[] ciphertext;
  byte[] iv;
  try {
    kg=KeyGenerator.getInstance("AES");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new PDCEncryptionException("No AES available",ex);
  }
  kg.init(128,random);
  secret_key=kg.generateKey();
  obj.put("0",wrapKey(public_key,secret_key));
  try {
    cipher=Cipher.getInstance("AES/CTR/PKCS7Padding");
    iv=new byte[cipher.getBlockSize()];
    random.nextBytes(iv);
    obj.put("1",iv);
    cipher.init(Cipher.ENCRYPT_MODE,secret_key,new IvParameterSpec(iv));
    ciphertext=cipher.doFinal(data);
    obj.put("2",ciphertext);
    return encoder.encode(obj);
  }
 catch (  GeneralSecurityException ex) {
    throw new PDCEncryptionException("Unable to encrypt message to " + public_key.toString(),ex);
  }
}
 

Example 58

From project Ohmage_Server_2, under directory /src/edu/ucla/cens/pdc/libpdc/util/.

Source file: EncryptionHelper.java

  17 
vote

public static byte[] encryptAsymData(PublicKey public_key,byte[] data) throws PDCEncryptionException {
  BSONEncoder encoder=new BSONEncoder();
  DBObject obj=new BasicDBList();
  SecureRandom random=new SecureRandom();
  KeyGenerator kg;
  Cipher cipher;
  SecretKey secret_key;
  byte[] ciphertext;
  byte[] iv;
  try {
    kg=KeyGenerator.getInstance("AES");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new PDCEncryptionException("No AES available",ex);
  }
  kg.init(128,random);
  secret_key=kg.generateKey();
  obj.put("0",wrapKey(public_key,secret_key));
  try {
    cipher=Cipher.getInstance("AES/CTR/PKCS7Padding");
    iv=new byte[cipher.getBlockSize()];
    random.nextBytes(iv);
    obj.put("1",iv);
    cipher.init(Cipher.ENCRYPT_MODE,secret_key,new IvParameterSpec(iv));
    ciphertext=cipher.doFinal(data);
    obj.put("2",ciphertext);
    return encoder.encode(obj);
  }
 catch (  GeneralSecurityException ex) {
    throw new PDCEncryptionException("Unable to encrypt message to " + public_key.toString(),ex);
  }
}
 

Example 59

From project Openbravo-POS-iPhone-App, under directory /OpenbravoPOS_PDA/src-pda/com/openbravo/pos/pda/util/.

Source file: CryptUtils.java

  17 
vote

/** 
 * Creates a new instance of Encrypter 
 */
public CryptUtils(String passPhrase){
  try {
    SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(passPhrase.getBytes("UTF8"));
    KeyGenerator kGen=KeyGenerator.getInstance("DESEDE");
    kGen.init(168,sr);
    Key key=kGen.generateKey();
    cipherDecrypt=Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
    cipherDecrypt.init(Cipher.DECRYPT_MODE,key);
  }
 catch (  UnsupportedEncodingException e) {
  }
catch (  NoSuchPaddingException e) {
  }
catch (  NoSuchAlgorithmException e) {
  }
catch (  InvalidKeyException e) {
  }
}
 

Example 60

From project openshift-java-client, under directory /src/main/java/com/openshift/internal/client/httpclient/.

Source file: UrlConnectionHttpClient.java

  17 
vote

/** 
 * Sets a trust manager that will always trust. <p> TODO: dont swallog exceptions and setup things so that they dont disturb other components.
 */
private void setPermissiveSSLSocketFactory(HttpsURLConnection connection){
  try {
    SSLContext sslContext=SSLContext.getInstance("SSL");
    sslContext.init(new KeyManager[0],new TrustManager[]{new PermissiveTrustManager()},new SecureRandom());
    SSLSocketFactory socketFactory=sslContext.getSocketFactory();
    ((HttpsURLConnection)connection).setSSLSocketFactory(socketFactory);
  }
 catch (  KeyManagementException e) {
  }
catch (  NoSuchAlgorithmException e) {
  }
}
 

Example 61

From project orion.server, under directory /bundles/org.eclipse.orion.server.core/src/org/eclipse/orion/server/core/resources/.

Source file: UniversalUniqueIdentifier.java

  17 
vote

/** 
 * Answers the node address attempting to mask the IP address of this machine.
 * @return byte[] the node address
 */
private static byte[] computeNodeAddress(){
  byte[] address=new byte[NODE_ADDRESS_BYTE_SIZE];
  int thread=Thread.currentThread().hashCode();
  long time=System.currentTimeMillis();
  int objectId=System.identityHashCode("");
  ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
  DataOutputStream out=new DataOutputStream(byteOut);
  byte[] ipAddress=getIPAddress();
  try {
    if (ipAddress != null)     out.write(ipAddress);
    out.write(thread);
    out.writeLong(time);
    out.write(objectId);
    out.close();
  }
 catch (  IOException exc) {
  }
  byte[] rand=byteOut.toByteArray();
  SecureRandom randomizer=new SecureRandom(rand);
  randomizer.nextBytes(address);
  address[0]=(byte)(address[0] | (byte)0x80);
  return address;
}
 

Example 62

From project p2-bridge, under directory /org.sonatype.p2.bridge.impl/src/main/java/org/sonatype/p2/bridge/internal/.

Source file: Utils.java

  17 
vote

static File createTempFile(final String prefix,final String suffix,final File parentDir){
  File result=null;
  String parent=System.getProperty("java.io.tmpdir");
  if (parentDir != null) {
    parent=parentDir.getPath();
  }
  final DecimalFormat fmt=new DecimalFormat("#####");
  final SecureRandom secureRandom=new SecureRandom();
  final long secureInitializer=secureRandom.nextLong();
  final Random rand=new Random(secureInitializer + Runtime.getRuntime().freeMemory());
synchronized (rand) {
    do {
      result=new File(parent,prefix + fmt.format(Math.abs(rand.nextInt())) + suffix);
    }
 while (result.exists());
  }
  return result;
}
 

Example 63

From project PenguinCMS, under directory /PenguinCMS/tests/vendor/sahi/src/net/sf/sahi/ssl/.

Source file: SSLHelper.java

  17 
vote

private SSLSocketFactory createSocketFactory(final String fileWithPath,final String password){
  SSLSocketFactory factory=null;
  try {
    KeyManagerFactory keyManagerFactory=getKeyManagerFactory(fileWithPath,password,"JKS");
    SSLContext sslContext=SSLContext.getInstance("SSLv3");
    sslContext.init(keyManagerFactory.getKeyManagers(),getAllTrustingManager(),new SecureRandom());
    factory=sslContext.getSocketFactory();
    return factory;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return (SSLSocketFactory)SSLSocketFactory.getDefault();
}
 

Example 64

From project platform_2, under directory /src/eu/cassandra/sim/utilities/.

Source file: RNG.java

  17 
vote

public static void init(){
  random=new SecureRandom();
  random.setSeed(System.currentTimeMillis());
  random.nextDouble();
  random.nextDouble();
  random.nextDouble();
  random.nextDouble();
  random.nextDouble();
}
 

Example 65

From project plexus-utils, under directory /src/main/java/org/codehaus/plexus/util/.

Source file: FileUtils.java

  17 
vote

/** 
 * Create a temporary file in a given directory. <p/> <p>The file denoted by the returned abstract pathname did not exist before this method was invoked, any subsequent invocation of this method will yield a different file name.</p> <p/> The filename is prefixNNNNNsuffix where NNNN is a random number </p> <p>This method is different to  {@link File#createTempFile(String,String,File)} of JDK 1.2as it doesn't create the file itself. It uses the location pointed to by java.io.tmpdir when the parentDir attribute is null.</p> <p>To delete automatically the file created by this method, use the {@link File#deleteOnExit()} method.</p>
 * @param prefix    prefix before the random number
 * @param suffix    file extension; include the '.'
 * @param parentDir Directory to create the temporary file in <code>-java.io.tmpdir</code>used if not specificed
 * @return a File reference to the new temporary file.
 */
public static File createTempFile(String prefix,String suffix,File parentDir){
  File result=null;
  String parent=System.getProperty("java.io.tmpdir");
  if (parentDir != null) {
    parent=parentDir.getPath();
  }
  DecimalFormat fmt=new DecimalFormat("#####");
  SecureRandom secureRandom=new SecureRandom();
  long secureInitializer=secureRandom.nextLong();
  Random rand=new Random(secureInitializer + Runtime.getRuntime().freeMemory());
synchronized (rand) {
    do {
      result=new File(parent,prefix + fmt.format(Math.abs(rand.nextInt())) + suffix);
    }
 while (result.exists());
  }
  return result;
}
 

Example 66

From project PocketMonstersOnline, under directory /Server/src/org/pokenet/server/battle/mechanics/.

Source file: BattleMechanics.java

  17 
vote

/** 
 * Initialise the battle mechanics. Try to use the SecureRandom class for the random number generator, with a seed from /dev/random. However, if /dev/random is unavailable (e.g. if we are running on Windows) then an instance of Random, seeded from the time, is used instead. For best results, use an operating system that supports /dev/random.
 */
public static Random getRandomSource(int bytes){
  try {
    return new SecureRandom();
  }
 catch (  Exception e) {
    System.out.println("Could not use SecureRandom: " + e.getMessage());
    return new Random();
  }
}
 

Example 67

From project qi4j-libraries, under directory /shiro-core/src/main/java/org/qi4j/library/shiro/domain/securehash/.

Source file: SecureHashFactory.java

  17 
vote

private String generateSalt(){
  try {
    Long salt=new SecureRandom().nextLong();
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    DataOutputStream dos=new DataOutputStream(bos);
    dos.writeLong(salt);
    dos.flush();
    return Base64.encodeToString(bos.toByteArray());
  }
 catch (  IOException ex) {
    throw new CryptoException(ex.getMessage(),ex);
  }
}
 

Example 68

From project remoting, under directory /src/main/java/hudson/remoting/.

Source file: Launcher.java

  17 
vote

private void runWithStdinStdout() throws IOException, InterruptedException {
  ttyCheck();
  if (isWindows()) {
    new SecureRandom().nextBoolean();
  }
  OutputStream os=new StandardOutputStream();
  System.setOut(System.err);
  main(System.in,os,mode,ping);
}
 

Example 69

From project repose, under directory /project-set/commons/utilities/src/main/java/com/rackspace/papi/commons/util/http/.

Source file: HttpsURLConnectionSslInitializer.java

  17 
vote

public void allowAllServerCerts(){
  TrustManager[] trustAllCerts=new TrustManager[]{new TrustingX509TrustManager()};
  try {
    final SSLContext sc=SSLContext.getInstance("SSL");
    sc.init(null,trustAllCerts,new SecureRandom());
    SSLContext.setDefault(sc);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  }
 catch (  Exception e) {
    LOG.error("Problem creating SSL context: ",e);
  }
}
 

Example 70

From project rest-client, under directory /src/main/java/org/hudsonci/rest/client/internal/ssl/.

Source file: TrustAllX509TrustManager.java

  17 
vote

public static synchronized void install() throws KeyManagementException, NoSuchAlgorithmException {
  SSLContext context=SSLContext.getInstance("SSL");
  context.init(null,new TrustManager[]{new TrustAllX509TrustManager()},new SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
  log.warn("Trust-all SSL trust manager installed");
}
 

Example 71

From project riak-java-client, under directory /src/main/java/com/basho/riak/pbc/.

Source file: RiakClient.java

  17 
vote

/** 
 * helper method to use a reasonable default client id beware, it caches the client id. If you call it multiple times on the same client you get the *same* id (not good for reusing a client with different ids)
 * @throws IOException
 */
public void prepareClientID() throws IOException {
  Preferences prefs=Preferences.userNodeForPackage(RiakClient.class);
  String clid=prefs.get("client_id",null);
  if (clid == null) {
    SecureRandom sr;
    try {
      sr=SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime());
    }
 catch (    NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
    byte[] data=new byte[6];
    sr.nextBytes(data);
    clid=CharsetUtils.asString(Base64.encodeBase64Chunked(data),CharsetUtils.ISO_8859_1);
    prefs.put("client_id",clid);
    try {
      prefs.flush();
    }
 catch (    BackingStoreException e) {
      throw new IOException(e.toString());
    }
  }
  setClientID(clid);
}
 

Example 72

From project rj-core, under directory /de.walware.rj.server/src/de/walware/rj/server/srvext/.

Source file: ServerAuthMethod.java

  17 
vote

public final void init(final String arg) throws RjException {
  try {
    if (this.usePubkeyExchange) {
      this.keyPairGenerator=KeyPairGenerator.getInstance("RSA");
      this.keyPairGenerator.initialize(2048);
    }
    this.randomGenerator=new SecureRandom();
    doInit(arg);
  }
 catch (  final Exception e) {
    final RjException rje=(e instanceof RjException) ? (RjException)e : new RjInitFailedException("An error occurred when initializing authentication method '" + this.id + "'.",e);
    throw rje;
  }
}
 

Example 73

From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.

Source file: PaymentProcessorForMtGox.java

  16 
vote

HttpsURLConnection setupConnection(String urlString){
  SSLContext ctx=null;
  try {
    ctx=SSLContext.getInstance("TLS");
  }
 catch (  NoSuchAlgorithmException e1) {
    e1.printStackTrace();
  }
  try {
    ctx.init(new KeyManager[0],new TrustManager[]{new DefaultTrustManager()},new SecureRandom());
  }
 catch (  KeyManagementException e) {
    e.printStackTrace();
  }
  SSLContext.setDefault(ctx);
  URL url=null;
  try {
    url=new URL(urlString);
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
  HttpsURLConnection conn=null;
  try {
    conn=(HttpsURLConnection)url.openConnection();
  }
 catch (  IOException e1) {
    e1.printStackTrace();
  }
  conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setHostnameVerifier(new HostnameVerifier(){
    @Override public boolean verify(    String arg0,    SSLSession arg1){
      return true;
    }
  }
);
  return conn;
}
 

Example 74

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/api/.

Source file: TrustAllSocketFactory.java

  16 
vote

public static SSLSocketFactory create(){
  try {
    SSLContext context=SSLContext.getInstance("SSL");
    context.init(null,new TrustManager[]{new X509TrustManager(){
      public void checkClientTrusted(      X509Certificate[] x509Certificates,      String authType) throws CertificateException {
      }
      public void checkServerTrusted(      X509Certificate[] x509Certificates,      String authType) throws CertificateException {
        if (LOGGER.isLoggable(FINE))         LOGGER.fine("Got the certificate: " + Arrays.asList(x509Certificates));
      }
      public X509Certificate[] getAcceptedIssuers(){
        return new X509Certificate[0];
      }
    }
},new SecureRandom());
    return context.getSocketFactory();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new Error(e);
  }
catch (  KeyManagementException e) {
    throw new Error(e);
  }
}
 

Example 75

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.

Source file: MicrosoftAzureSSLHelper.java

  16 
vote

/** 
 * @return .
 * @throws NoSuchAlgorithmException .
 * @throws KeyStoreException .
 * @throws CertificateException .
 * @throws IOException .
 * @throws UnrecoverableKeyException .
 * @throws KeyManagementException .
 */
public SSLContext createSSLContext() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
  InputStream pfxFile=null;
  SSLContext context=null;
  try {
    pfxFile=new FileInputStream(new File(pathToPfxFile));
    KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(SUN_X_509_ALGORITHM);
    KeyStore keyStore=KeyStore.getInstance(KEY_STORE_CONTEXT);
    keyStore.load(pfxFile,pfxPassword.toCharArray());
    pfxFile.close();
    keyManagerFactory.init(keyStore,pfxPassword.toCharArray());
    context=SSLContext.getInstance("SSL");
    context.init(keyManagerFactory.getKeyManagers(),null,new SecureRandom());
    return context;
  }
  finally {
    if (pfxFile != null) {
      pfxFile.close();
    }
  }
}
 

Example 76

From project gecko, under directory /src/test/java/com/taobao/gecko/core/nio/impl/.

Source file: TimerRefQueueUnitTest.java

  16 
vote

@Test public void testCancel() throws Exception {
  final int count=100000;
  final List<TimerRef> list=new ArrayList<TimerRef>();
  for (int i=0; i < count; i++) {
    final TimerRef timer=new TimerRef(i,null);
    this.queue.add(timer);
    list.add(timer);
  }
  final CyclicBarrier barrier=new CyclicBarrier(2001);
  final List<IterateThread> iterateThreads=new ArrayList<IterateThread>();
  for (int i=0; i < 1000; i++) {
    final IterateThread iterateThread=new IterateThread(barrier,count);
    iterateThreads.add(iterateThread);
    iterateThread.start();
  }
  final Random rand=new SecureRandom();
  for (int i=0; i < 1000; i++) {
    final Thread thread=new CancelThread(list,barrier,rand);
    thread.start();
  }
  barrier.await();
  barrier.await();
  for (  final IterateThread iterateThread : iterateThreads) {
    assertTrue(iterateThread.end);
  }
}
 

Example 77

From project gitblit, under directory /src/com/gitblit/.

Source file: MakeCertificate.java

  16 
vote

public static void generateSelfSignedCertificate(String hostname,File keystore,String keystorePassword){
  try {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator kpGen=KeyPairGenerator.getInstance("RSA","BC");
    kpGen.initialize(1024,new SecureRandom());
    KeyPair pair=kpGen.generateKeyPair();
    X500NameBuilder builder=new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.OU,Constants.NAME);
    builder.addRDN(BCStyle.O,Constants.NAME);
    builder.addRDN(BCStyle.CN,hostname);
    Date notBefore=new Date(System.currentTimeMillis() - TimeUtils.ONEDAY);
    Date notAfter=new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
    BigInteger serial=BigInteger.valueOf(System.currentTimeMillis());
    X509v3CertificateBuilder certGen=new JcaX509v3CertificateBuilder(builder.build(),serial,notBefore,notAfter,builder.build(),pair.getPublic());
    ContentSigner sigGen=new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(pair.getPrivate());
    X509Certificate cert=new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());
    KeyStore store=KeyStore.getInstance("JKS");
    if (keystore.exists()) {
      FileInputStream fis=new FileInputStream(keystore);
      store.load(fis,keystorePassword.toCharArray());
      fis.close();
    }
 else {
      store.load(null);
    }
    store.setKeyEntry(hostname,pair.getPrivate(),keystorePassword.toCharArray(),new java.security.cert.Certificate[]{cert});
    FileOutputStream fos=new FileOutputStream(keystore);
    store.store(fos,keystorePassword.toCharArray());
    fos.close();
  }
 catch (  Throwable t) {
    t.printStackTrace();
    throw new RuntimeException("Failed to generate self-signed certificate!",t);
  }
}
 

Example 78

From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/haven/.

Source file: SslHelper.java

  16 
vote

private synchronized SSLContext ctx(){
  if (ctx == null) {
    TrustManagerFactory tmf;
    KeyManagerFactory kmf;
    try {
      ctx=SSLContext.getInstance("TLS");
      tmf=TrustManagerFactory.getInstance("PKIX");
      kmf=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      KeyManager[] kms=null;
      tmf.init(trusted);
      if (creds != null) {
        kmf.init(creds,pw);
        kms=kmf.getKeyManagers();
      }
      ctx.init(kms,tmf.getTrustManagers(),new SecureRandom());
    }
 catch (    NoSuchAlgorithmException e) {
      throw (new Error(e));
    }
catch (    KeyStoreException e) {
      throw (new RuntimeException(e));
    }
catch (    UnrecoverableKeyException e) {
      throw (new RuntimeException(e));
    }
catch (    KeyManagementException e) {
      throw (new RuntimeException(e));
    }
  }
  return (ctx);
}
 

Example 79

From project hawtdispatch, under directory /hawtdispatch-example/src/main/scala/org/fusesource/hawtdispatch/example/.

Source file: SSLClientExample.java

  16 
vote

public static void main(String[] args) throws Exception {
  SSLContext sslContext=SSLContext.getInstance("SSL");
  sslContext.init(null,TRUST_ALL_CERTS,new SecureRandom());
  final SslTransport client=new SslTransport();
  client.setDispatchQueue(Dispatch.createQueue());
  client.setSSLContext(sslContext);
  client.setBlockingExecutor(Executors.newCachedThreadPool());
  client.setProtocolCodec(new BufferProtocolCodec());
  client.connecting(new URI("ssl://localhost:61614"),null);
  final CountDownLatch done=new CountDownLatch(1);
  final Task onClose=new Task(){
    public void run(){
      System.out.println("Client closed.");
      done.countDown();
    }
  }
;
  client.setTransportListener(new DefaultTransportListener(){
    @Override public void onTransportConnected(){
      System.out.println("Connected");
      client.resumeRead();
      client.offer(new AsciiBuffer("CONNECT\n" + "login:admin\n" + "passcode:password\n"+ "\n\u0000\n"));
    }
    @Override public void onTransportCommand(    Object command){
      Buffer frame=(Buffer)command;
      System.out.println("Received :" + frame.ascii());
      client.stop(onClose);
    }
    @Override public void onTransportFailure(    IOException error){
      System.out.println("Transport failure :" + error);
      client.stop(onClose);
    }
  }
);
  client.start(Dispatch.NOOP);
  done.await();
}
 

Example 80

From project hotpotato, under directory /src/main/java/com/biasedbit/hotpotato/util/.

Source file: DummyHttpServer.java

  16 
vote

public static SslHandler createSelfSignedSslHandler() throws Exception {
  String algorithm="SunX509";
  String password="password";
  KeyStore keyStore=KeyStore.getInstance("JKS");
  InputStream keyStoreAsStream=null;
  try {
    keyStoreAsStream=new BufferedInputStream(new FileInputStream("src/main/resources/dummyserver/selfsigned.jks"));
    keyStore.load(keyStoreAsStream,password.toCharArray());
  }
  finally {
    if (keyStoreAsStream != null) {
      try {
        keyStoreAsStream.close();
      }
 catch (      Exception e) {
      }
    }
  }
  KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(algorithm);
  TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(algorithm);
  keyManagerFactory.init(keyStore,password.toCharArray());
  trustManagerFactory.init(keyStore);
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),new SecureRandom());
  SSLEngine engine=context.createSSLEngine();
  engine.setUseClientMode(false);
  return new SslHandler(engine,true);
}
 

Example 81

From project http-client, under directory /src/main/java/com/biasedbit/http/ssl/.

Source file: DefaultSslContextFactory.java

  16 
vote

public DefaultSslContextFactory build() throws Exception {
  if (this.algorithm == null) {
    this.algorithm="SunX509";
  }
  if (protocol == null) {
    this.protocol="TLSv1";
  }
  if (this.store == null) {
    this.store=KeyStore.getInstance("JKS");
  }
  this.store.load(this.keyAsInputStream,(this.keyStorePassword == null) ? null : this.keyStorePassword.toCharArray());
  KeyManagerFactory keyMgrFactory=KeyManagerFactory.getInstance(algorithm);
  keyMgrFactory.init(this.store,(this.certificatePassword == null) ? null : this.certificatePassword.toCharArray());
  TrustManagerFactory trustMgrFactory=TrustManagerFactory.getInstance(this.algorithm);
  trustMgrFactory.init(this.store);
  SSLContext serverContext=SSLContext.getInstance(this.protocol);
  SSLContext clientContext=SSLContext.getInstance(this.protocol);
  serverContext.init(keyMgrFactory.getKeyManagers(),trustMgrFactory.getTrustManagers(),new SecureRandom());
  clientContext.init(keyMgrFactory.getKeyManagers(),trustMgrFactory.getTrustManagers(),new SecureRandom());
  return new DefaultSslContextFactory(serverContext,clientContext);
}
 

Example 82

From project iSpace, under directory /base/httpcrawler/src/main/java/com/villemos/ispace/httpcrawler/.

Source file: HttpClientConfigurer.java

  16 
vote

public static HttpClient setupClient(boolean ignoreAuthenticationFailure,String domain,Integer port,String proxyHost,Integer proxyPort,String authUser,String authPassword,CookieStore cookieStore) throws NoSuchAlgorithmException, KeyManagementException {
  DefaultHttpClient client=null;
  if (ignoreAuthenticationFailure) {
    SSLContext sslContext=SSLContext.getInstance("SSL");
    sslContext.init(null,new TrustManager[]{new EasyX509TrustManager()},new SecureRandom());
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    SSLSocketFactory sf=new SSLSocketFactory(sslContext);
    Scheme httpsScheme=new Scheme("https",sf,443);
    schemeRegistry.register(httpsScheme);
    SocketFactory sfa=new PlainSocketFactory();
    Scheme httpScheme=new Scheme("http",sfa,80);
    schemeRegistry.register(httpScheme);
    HttpParams params=new BasicHttpParams();
    ClientConnectionManager cm=new SingleClientConnManager(params,schemeRegistry);
    client=new DefaultHttpClient(cm,params);
  }
 else {
    client=new DefaultHttpClient();
  }
  if (proxyHost != null && proxyPort != null) {
    HttpHost proxy=new HttpHost(proxyHost,proxyPort);
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
  }
 else {
    ProxySelectorRoutePlanner routePlanner=new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);
  }
  if (authUser != null && authPassword != null) {
    client.getCredentialsProvider().setCredentials(new AuthScope(domain,port),new UsernamePasswordCredentials(authUser,authPassword));
  }
  client.setCookieStore(cookieStore);
  client.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BEST_MATCH);
  return client;
}
 

Example 83

From project java-maven-tests, under directory /src/lang-samples/mem-lock-eval/src/main/java/com/alexshabanov/memlock/.

Source file: App.java

  16 
vote

private static void testBarAlloc() throws IOException {
  printMemUsage("enter testBarAlloc");
  final Bar[] barChunk=new Bar[ARR_SIZE];
  final long before=System.currentTimeMillis();
  for (int j=0; j < ARR_SIZE; ++j) {
    final Bar bar=new Bar();
    bar.setA(-j);
    bar.setB(1 + j);
    barChunk[j]=bar;
  }
  final long total=System.currentTimeMillis() - before;
  System.out.println(MessageFormat.format("Bar alloc done; total time: {0}",total));
  printMemUsage("bar alloc iteration");
  System.out.println("Press key to continue");
  System.in.read();
{
    final Random random=new SecureRandom();
    final Bar randBar=barChunk[random.nextInt(ARR_SIZE)];
    System.out.println("RandBar = " + randBar);
  }
}
 

Example 84

From project karaf, under directory /jaas/config/src/main/java/org/apache/karaf/jaas/config/impl/.

Source file: OsgiKeystoreManager.java

  16 
vote

public SSLContext createSSLContext(String provider,String protocol,String algorithm,String keyStore,String keyAlias,String trustStore,long timeout) throws GeneralSecurityException {
  if (!this.checkForKeystoresAvailability(keyStore,keyAlias,trustStore,timeout)) {
    throw new GeneralSecurityException("Unable to lookup configured keystore and/or truststore");
  }
  KeystoreInstance keyInstance=getKeystore(keyStore);
  if (keyInstance != null && keyInstance.isKeystoreLocked()) {
    throw new KeystoreIsLocked("Keystore '" + keyStore + "' is locked");
  }
  if (keyInstance != null && keyInstance.isKeyLocked(keyAlias)) {
    throw new KeystoreIsLocked("Key '" + keyAlias + "' in keystore '"+ keyStore+ "' is locked");
  }
  KeystoreInstance trustInstance=trustStore == null ? null : getKeystore(trustStore);
  if (trustInstance != null && trustInstance.isKeystoreLocked()) {
    throw new KeystoreIsLocked("Keystore '" + trustStore + "' is locked");
  }
  SSLContext context;
  if (provider == null) {
    context=SSLContext.getInstance(protocol);
  }
 else {
    context=SSLContext.getInstance(protocol,provider);
  }
  context.init(keyInstance == null ? null : keyInstance.getKeyManager(algorithm,keyAlias),trustInstance == null ? null : trustInstance.getTrustManager(algorithm),new SecureRandom());
  return context;
}
 

Example 85

From project libgrowl, under directory /src/main/java/net/sf/libgrowl/internal/.

Source file: Encryption.java

  16 
vote

/** 
 * get key hash for password GNTP Spec - http://www.growlforwindows.com/gfw/help/gntp.aspx GNTp Key Checker - http://www.growlforwindows.com/gfw/help/keychecker.aspx
 * @param password
 * @return key hash as String <code>""</code>
 */
public static String generateKeyHash(final String password){
  MessageDigest md5;
  String keyhash="";
  byte[] passBytes=password.getBytes();
  Random r=new SecureRandom();
  byte[] salt=new byte[14];
  r.nextBytes(salt);
  ByteBuffer bb=ByteBuffer.allocate(passBytes.length + salt.length);
  bb.put(passBytes);
  bb.put(salt);
  try {
    md5=MessageDigest.getInstance("MD5");
    md5.reset();
    md5.update(bb.array());
    final byte[] result=md5.digest();
    keyhash=md5(result);
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  keyhash=keyhash + "." + buildHexString(salt);
  return keyhash;
}
 

Example 86

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/oauth/server/src/main/java/demo/oauth/server/controllers/.

Source file: ApplicationController.java

  16 
vote

@RequestMapping("/registerClient") public ModelAndView registerApp(@ModelAttribute("client") ClientApp clientApp) throws Exception {
  if (StringUtils.isEmpty(clientApp.getClientName())) {
    clientApp.setError("Client name field is required!");
    return handleInternalRedirect(clientApp);
  }
  MD5SequenceGenerator tokenGen=new MD5SequenceGenerator();
  Principal principal=SecurityContextHolder.getContext().getAuthentication();
  String consumerKey=clientApp.getConsumerKey();
  if (StringUtils.isEmpty(consumerKey)) {
    consumerKey=tokenGen.generate((principal.getName() + clientApp.getClientName()).getBytes("UTF-8"));
  }
  String secretKey=tokenGen.generate(new SecureRandom().generateSeed(20));
  Client clientInfo=new Client(consumerKey,secretKey,clientApp.getClientName(),clientApp.getCallbackURL());
  clientInfo.setLoginName(principal.getName());
  Client authNInfo=clientManager.registerNewClient(consumerKey,clientInfo);
  if (authNInfo != null) {
    clientApp.setError("Client already exists!");
    return handleInternalRedirect(clientApp);
  }
  ModelAndView modelAndView=new ModelAndView("clientDetails");
  modelAndView.getModel().put("clientInfo",clientInfo);
  return modelAndView;
}
 

Example 87

From project LoL-Chat, under directory /src/com/rei/lolchat/.

Source file: BeemService.java

  16 
vote

public static void allowAllSSL(){
  HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
    public boolean verify(    String hostname,    SSLSession session){
      return true;
    }
  }
);
  if (trustManagers == null) {
    trustManagers=new TrustManager[]{new FakeX509TrustManager()};
  }
  try {
    context=SSLContext.getInstance("TLS");
    context.init(null,trustManagers,new SecureRandom());
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
catch (  KeyManagementException e) {
    e.printStackTrace();
  }
  HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
 

Example 88

From project Mobile-Tour-Guide, under directory /zxing-2.0/core/test/src/com/google/zxing/common/.

Source file: BitArrayTestCase.java

  16 
vote

@Test public void testGetNextSet5(){
  Random r=new SecureRandom(new byte[]{(byte)0xDE,(byte)0xAD,(byte)0xBE,(byte)0xEF});
  for (int i=0; i < 10; i++) {
    BitArray array=new BitArray(1 + r.nextInt(100));
    int numSet=r.nextInt(20);
    for (int j=0; j < numSet; j++) {
      array.set(r.nextInt(array.getSize()));
    }
    int numQueries=r.nextInt(20);
    for (int j=0; j < numQueries; j++) {
      int query=r.nextInt(array.getSize());
      int expected=query;
      while (expected < array.getSize() && !array.get(expected)) {
        expected++;
      }
      int actual=array.getNextSet(query);
      if (actual != expected) {
        array.getNextSet(query);
      }
      assertEquals(expected,actual);
    }
  }
}
 

Example 89

From project osgi-tests, under directory /test/glassfish-derby/src/test/java/org/ancoron/osgi/test/glassfish/.

Source file: GlassfishDerbyTest.java

  16 
vote

protected DefaultHttpClient getHTTPClient() throws NoSuchAlgorithmException, KeyManagementException {
  SSLContext sslContext=SSLContext.getInstance("SSL");
  sslContext.init(null,new TrustManager[]{new X509TrustManager(){
    @Override public X509Certificate[] getAcceptedIssuers(){
      System.out.println("getAcceptedIssuers =============");
      return null;
    }
    @Override public void checkClientTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkClientTrusted =============");
    }
    @Override public void checkServerTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkServerTrusted =============");
    }
  }
},new SecureRandom());
  SSLSocketFactory sf=new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  Scheme httpsScheme=new Scheme("https",8181,sf);
  PlainSocketFactory plain=new PlainSocketFactory();
  Scheme httpScheme=new Scheme("http",8080,plain);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(httpsScheme);
  schemeRegistry.register(httpScheme);
  HttpParams params=new BasicHttpParams();
  ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(schemeRegistry);
  cm.setMaxTotal(200);
  cm.setDefaultMaxPerRoute(20);
  DefaultHttpClient httpClient=new DefaultHttpClient(cm,params);
  httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
  httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,"UTF-8");
  return httpClient;
}
 

Example 90

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/httpclient/.

Source file: SSLContextManager.java

  16 
vote

/** 
 * Creates a new instance of SSLContextManager 
 */
public SSLContextManager(){
  System.setProperty("sun.security.ssl.allowUnsafeRenegotiation","true");
  try {
    _noClientCertContext=SSLContext.getInstance("SSL");
    _noClientCertContext.init(null,_trustAllCerts,new SecureRandom());
  }
 catch (  NoSuchAlgorithmException nsao) {
    _logger.severe("Could not get an instance of the SSL algorithm: " + nsao.getMessage());
  }
catch (  KeyManagementException kme) {
    _logger.severe("Error initialising the SSL Context: " + kme);
  }
  try {
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      initPKCS11("P11-CAPI","lib/p11-capi.dll",0,"");
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 91

From project processFlowProvision, under directory /osProvision/src/main/java/org/jboss/processFlow/openshift/.

Source file: ShifterProvisioner.java

  16 
vote

private void prepConnection() throws Exception {
  httpClient=new DefaultHttpClient();
  SSLContext sslContext=SSLContext.getInstance("SSL");
  sslContext.init(null,new TrustManager[]{new X509TrustManager(){
    public X509Certificate[] getAcceptedIssuers(){
      System.out.println("getAcceptedIssuers =============");
      return null;
    }
    public void checkClientTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkClientTrusted =============");
    }
    public void checkServerTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkServerTrusted =============");
    }
  }
},new SecureRandom());
  SSLSocketFactory ssf=new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  ClientConnectionManager ccm=httpClient.getConnectionManager();
  SchemeRegistry sr=ccm.getSchemeRegistry();
  sr.register(new Scheme("https",443,ssf));
  UsernamePasswordCredentials credentials=new UsernamePasswordCredentials(accountId,password);
  URL urlObj=new URL(openshiftRestURI);
  AuthScope aScope=new AuthScope(urlObj.getHost(),urlObj.getPort());
  httpClient.getCredentialsProvider().setCredentials(aScope,credentials);
  httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(),0);
}
 

Example 92

From project recordloader, under directory /src/java/com/marklogic/ps/.

Source file: Crypto.java

  16 
vote

public static void encryptPassword(String password) throws Exception {
  KeyGenerator kg=KeyGenerator.getInstance("DES");
  kg.init(new SecureRandom());
  SecretKey key=kg.generateKey();
  SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
  Class spec=Class.forName("javax.crypto.spec.DESKeySpec");
  DESKeySpec ks=(DESKeySpec)skf.getKeySpec(key,spec);
  ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("keyfile"));
  oos.writeObject(ks.getKey());
  Cipher c=Cipher.getInstance("DES/CFB8/NoPadding");
  c.init(Cipher.ENCRYPT_MODE,key);
  CipherOutputStream cos=new CipherOutputStream(new FileOutputStream("ciphertext"),c);
  PrintWriter pw=new PrintWriter(new OutputStreamWriter(cos));
  pw.println(password);
  pw.close();
  oos.writeObject(c.getIV());
  oos.close();
}
 

Example 93

From project red5-server, under directory /src/org/red5/server/net/rtmps/.

Source file: RTMPSMinaIoHandler.java

  16 
vote

/** 
 * {@inheritDoc} 
 */
@Override public void sessionOpened(IoSession session) throws Exception {
  if (password == null || keystore == null) {
    throw new NotActiveException("Keystore or password are null");
  }
  SSLContext context=null;
  SslFilter sslFilter=null;
  RTMP rtmp=(RTMP)session.getAttribute(ProtocolState.SESSION_KEY);
  if (rtmp.getMode() != RTMP.MODE_CLIENT) {
    context=SSLContext.getInstance("TLS");
    KeyManagerFactory kmf=KeyManagerFactory.getInstance("SunX509");
    kmf.init(getKeyStore(),password);
    context.init(kmf.getKeyManagers(),null,null);
    sslFilter=new SslFilter(context);
  }
 else {
    context=SSLContext.getInstance("SSL");
    context.init(null,trustAllCerts,new SecureRandom());
    sslFilter=new SslFilter(context);
    sslFilter.setUseClientMode(true);
  }
  if (sslFilter != null) {
    session.getFilterChain().addFirst("sslFilter",sslFilter);
  }
  super.sessionOpened(session);
}
 

Example 94

From project restfuse, under directory /com.eclipsesource.restfuse/src/com/github/kevinsawicki/http/.

Source file: HttpRequest.java

  16 
vote

private static SSLSocketFactory getTrustedFactory() throws HttpRequestException {
  if (TRUSTED_FACTORY == null) {
    final TrustManager[] trustAllCerts=new TrustManager[]{new X509TrustManager(){
      public X509Certificate[] getAcceptedIssuers(){
        return new X509Certificate[0];
      }
      public void checkClientTrusted(      X509Certificate[] chain,      String authType){
      }
      public void checkServerTrusted(      X509Certificate[] chain,      String authType){
      }
    }
};
    try {
      SSLContext context=SSLContext.getInstance("TLS");
      context.init(null,trustAllCerts,new SecureRandom());
      TRUSTED_FACTORY=context.getSocketFactory();
    }
 catch (    GeneralSecurityException e) {
      IOException ioException=new IOException("Security exception configuring SSL context");
      ioException.initCause(e);
      throw new HttpRequestException(ioException);
    }
  }
  return TRUSTED_FACTORY;
}
 

Example 95

From project accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: BCrypt.java

  15 
vote

/** 
 * Generate a salt for use with the BCrypt.hashpw() method
 * @param log_rounds	the log2 of the number of rounds ofhashing to apply - the work factor therefore increases as 2**log_rounds.
 * @param random		an instance of SecureRandom to use
 * @return	an encoded salt value
 */
public static String gensalt(int log_rounds,SecureRandom random){
  StringBuffer rs=new StringBuffer();
  byte rnd[]=new byte[BCRYPT_SALT_LEN];
  random.nextBytes(rnd);
  rs.append("$2a$");
  if (log_rounds < 10)   rs.append("0");
  rs.append(Integer.toString(log_rounds));
  rs.append("$");
  rs.append(encode_base64(rnd,rnd.length));
  return rs.toString();
}
 

Example 96

From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.

Source file: SslContext.java

  15 
vote

public SslContext(KeyManager[] km,TrustManager[] tm,SecureRandom random){
  if (km != null) {
    setKeyManagers(Arrays.asList(km));
  }
  if (tm != null) {
    setTrustManagers(Arrays.asList(tm));
  }
  setSecureRandom(random);
}
 

Example 97

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: GUID.java

  15 
vote

/** 
 * Get SecureRandom instance for creation of random number.
 * @param algo the String algorithm specification (e.g. "SHA1PRNG") for creation of the SecureRandom instance
 * @param provider the provider of the implementation of the given algorighm (e.g. "SUN")
 * @return SecureRandom
 * @exception Exception thrown if SecureRandom instance cannot be created/accessed
 */
protected static synchronized SecureRandom getRandom(String algo,String provider) throws Exception {
  if (random == null) {
    initializeRandom(algo,provider);
  }
  return random;
}
 

Example 98

From project etherpad, under directory /infrastructure/net.appjet.common/util/.

Source file: BCrypt.java

  15 
vote

/** 
 * Generate a salt for use with the BCrypt.hashpw() method
 * @param log_rounds	the log2 of the number of rounds ofhashing to apply - the work factor therefore increases as 2**log_rounds.
 * @param random		an instance of SecureRandom to use
 * @return	an encoded salt value
 */
public static String gensalt(int log_rounds,SecureRandom random){
  StringBuffer rs=new StringBuffer();
  byte rnd[]=new byte[BCRYPT_SALT_LEN];
  random.nextBytes(rnd);
  rs.append("$2a$");
  if (log_rounds < 10)   rs.append("0");
  rs.append(Integer.toString(log_rounds));
  rs.append("$");
  rs.append(encode_base64(rnd,rnd.length));
  return rs.toString();
}
 

Example 99

From project heritrix3, under directory /engine/src/test/java/org/archive/crawler/selftest/.

Source file: SelfTestBase.java

  15 
vote

protected void startHeritrix(String path) throws Exception {
  String authPassword=(new BigInteger(SecureRandom.getSeed(16))).abs().toString(16);
  String[] args={"-j",path + "/jobs","-a",authPassword};
  heritrix=new Heritrix();
  heritrix.instanceMain(args);
  configureHeritrix();
  heritrix.getEngine().requestLaunch("selftest-job");
}
 

Example 100

From project jetty-project, under directory /jetty-jboss/src/main/java/org/mortbay/j2ee/session/.

Source file: GUIDGenerator.java

  15 
vote

/** 
 * get a random-number generator
 * @return a random-number generator
 */
protected synchronized Random getRandom(){
  long seed;
  Random random=null;
  seed=System.currentTimeMillis();
  seed^=Runtime.getRuntime().freeMemory();
  try {
    random=SecureRandom.getInstance(SESSION_ID_RANDOM_ALGORITHM);
  }
 catch (  NoSuchAlgorithmException e) {
    try {
      random=SecureRandom.getInstance(SESSION_ID_RANDOM_ALGORITHM_ALT);
    }
 catch (    NoSuchAlgorithmException e_alt) {
      _log.error("Could not generate SecureRandom for session-id randomness",e);
      _log.error("Could not generate SecureRandom for session-id randomness",e_alt);
      return null;
    }
  }
  random.setSeed(seed);
  return random;
}
 

Example 101

From project jPOS, under directory /jpos/src/main/java/org/jpos/iso/.

Source file: SunJSSESocketFactory.java

  15 
vote

/** 
 * Create a SSLSocket Context
 * @return the SSLContext
 * @returns null if exception occurrs
 */
private SSLContext getSSLContext() throws ISOException {
  if (password == null)   password=getPassword();
  if (keyPassword == null)   keyPassword=getKeyPassword();
  if (keyStore == null || keyStore.length() == 0) {
    keyStore=System.getProperty("user.home") + File.separator + ".keystore";
  }
  try {
    KeyStore ks=KeyStore.getInstance("JKS");
    FileInputStream fis=new FileInputStream(new File(keyStore));
    ks.load(fis,password.toCharArray());
    fis.close();
    KeyManagerFactory km=KeyManagerFactory.getInstance("SunX509");
    km.init(ks,keyPassword.toCharArray());
    KeyManager[] kma=km.getKeyManagers();
    TrustManager[] tma=getTrustManagers(ks);
    SSLContext sslc=SSLContext.getInstance("SSL");
    sslc.init(kma,tma,SecureRandom.getInstance("SHA1PRNG"));
    return sslc;
  }
 catch (  Exception e) {
    throw new ISOException(e);
  }
 finally {
    password=null;
    keyPassword=null;
  }
}
 

Example 102

From project jsmpp, under directory /jsmpp/src/main/java/org/jsmpp/util/.

Source file: RandomMessageIDGenerator.java

  15 
vote

public RandomMessageIDGenerator(){
  try {
    random=SecureRandom.getInstance("SHA1PRNG");
  }
 catch (  NoSuchAlgorithmException e) {
    random=new Random();
  }
}
 

Example 103

From project keepassdroid, under directory /src/com/keepassdroid/crypto/.

Source file: NativeAESCipherSpi.java

  15 
vote

@Override protected void engineInit(int opmode,Key key,AlgorithmParameterSpec params,SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
  IvParameterSpec ivparam;
  if (params instanceof IvParameterSpec) {
    ivparam=(IvParameterSpec)params;
  }
 else {
    throw new InvalidAlgorithmParameterException("params must be an IvParameterSpec.");
  }
  init(opmode,key,ivparam);
}
 

Example 104

From project org.ops4j.pax.useradmin, under directory /pax-useradmin-service/src/main/java/org/ops4j/pax/useradmin/service/internal/.

Source file: EncryptorImpl.java

  15 
vote

/** 
 * Initializing constructor.
 * @param algorithm The name of the encryption algorithm to use.
 * @param rngAlgorithm The random-number generator algorithm to use.
 * @param saltLength The length of the salt.
 * @throws NoSuchAlgorithmException Thrown if a specified algorithm is not available.
 */
protected EncryptorImpl(String algorithm,String rngAlgorithm,String saltLength) throws NoSuchAlgorithmException {
  if (null == algorithm || "".equals(algorithm)) {
    throw new IllegalArgumentException("Error: parameter algorithm must no be null or empty.");
  }
  if (null == rngAlgorithm || "".equals(rngAlgorithm)) {
    throw new IllegalArgumentException("Error: parameter rngAlgorithm must no be null or empty.");
  }
  if (null == saltLength || "".equals(saltLength)) {
    throw new IllegalArgumentException("Error: parameter saltLength must no be null or empty.");
  }
  m_messageDigest=MessageDigest.getInstance(algorithm);
  m_saltLength=new Integer(saltLength);
  m_secureRandom=SecureRandom.getInstance(rngAlgorithm);
  m_secureRandom.setSeed(System.currentTimeMillis());
}
 

Example 105

From project Orweb, under directory /src/info/guardianproject/browser/.

Source file: ModSSLSocketFactory.java

  15 
vote

public ModSSLSocketFactory(String algorithm,final KeyStore keystore,final String keystorePassword,final KeyStore truststore,final SecureRandom random,final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  super();
  if (algorithm == null) {
    algorithm=TLS;
  }
  KeyManager[] keymanagers=null;
  if (keystore != null) {
    keymanagers=createKeyManagers(keystore,keystorePassword);
  }
  TrustManager[] trustmanagers=null;
  if (truststore != null) {
    trustmanagers=createTrustManagers(truststore);
  }
  this.sslcontext=SSLContext.getInstance(algorithm);
  this.sslcontext.init(keymanagers,trustmanagers,random);
  this.socketfactory=this.sslcontext.getSocketFactory();
  this.nameResolver=nameResolver;
}
 

Example 106

From project pad, under directory /infrastructure/net.appjet.common/util/.

Source file: BCrypt.java

  15 
vote

/** 
 * Generate a salt for use with the BCrypt.hashpw() method
 * @param log_rounds	the log2 of the number of rounds ofhashing to apply - the work factor therefore increases as 2**log_rounds.
 * @param random		an instance of SecureRandom to use
 * @return	an encoded salt value
 */
public static String gensalt(int log_rounds,SecureRandom random){
  StringBuffer rs=new StringBuffer();
  byte rnd[]=new byte[BCRYPT_SALT_LEN];
  random.nextBytes(rnd);
  rs.append("$2a$");
  if (log_rounds < 10)   rs.append("0");
  rs.append(Integer.toString(log_rounds));
  rs.append("$");
  rs.append(encode_base64(rnd,rnd.length));
  return rs.toString();
}
 

Example 107

From project passfault, under directory /core/test/com/passfault/.

Source file: BCrypt.java

  15 
vote

/** 
 * Generate a salt for use with the BCrypt.hashpw() method
 * @param log_rounds	the log2 of the number of rounds ofhashing to apply - the work factor therefore increases as 2**log_rounds.
 * @param random		an instance of SecureRandom to use
 * @return	an encoded salt value
 */
public static String gensalt(int log_rounds,SecureRandom random){
  StringBuffer rs=new StringBuffer();
  byte rnd[]=new byte[BCRYPT_SALT_LEN];
  random.nextBytes(rnd);
  rs.append("$2a$");
  if (log_rounds < 10)   rs.append("0");
  rs.append(Integer.toString(log_rounds));
  rs.append("$");
  rs.append(encode_base64(rnd,rnd.length));
  return rs.toString();
}
 

Example 108

From project pdftk, under directory /java/org/bouncycastle/util/.

Source file: BigIntegers.java

  15 
vote

/** 
 * Return a random BigInteger not less than 'min' and not greater than 'max'
 * @param min the least value that may be generated
 * @param max the greatest value that may be generated
 * @param random the source of randomness
 * @return a random BigInteger value in the range [min,max]
 */
public static BigInteger createRandomInRange(BigInteger min,BigInteger max,SecureRandom random){
  int cmp=min.compareTo(max);
  if (cmp >= 0) {
    if (cmp > 0) {
      throw new IllegalArgumentException("'min' may not be greater than 'max'");
    }
    return min;
  }
  if (min.bitLength() > max.bitLength() / 2) {
    return createRandomInRange(ZERO,max.subtract(min),random).add(min);
  }
  for (int i=0; i < MAX_ITERATIONS; ++i) {
    BigInteger x=new BigInteger(max.bitLength(),random);
    if (x.compareTo(min) >= 0 && x.compareTo(max) <= 0) {
      return x;
    }
  }
  return new BigInteger(max.subtract(min).bitLength() - 1,random).add(min);
}
 

Example 109

From project platform_external_apache-http, under directory /src/org/apache/http/conn/ssl/.

Source file: SSLSocketFactory.java

  15 
vote

public SSLSocketFactory(String algorithm,final KeyStore keystore,final String keystorePassword,final KeyStore truststore,final SecureRandom random,final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  super();
  if (algorithm == null) {
    algorithm=TLS;
  }
  KeyManager[] keymanagers=null;
  if (keystore != null) {
    keymanagers=createKeyManagers(keystore,keystorePassword);
  }
  TrustManager[] trustmanagers=null;
  if (truststore != null) {
    trustmanagers=createTrustManagers(truststore);
  }
  this.sslcontext=SSLContext.getInstance(algorithm);
  this.sslcontext.init(keymanagers,trustmanagers,random);
  this.socketfactory=this.sslcontext.getSocketFactory();
  this.nameResolver=nameResolver;
}
 

Example 110

From project pos_1, under directory /jetty/contrib/cometd/bayeux/src/main/java/org/mortbay/cometd/.

Source file: AbstractBayeux.java

  15 
vote

protected void initialize(ServletContext context){
synchronized (this) {
    _initialized=true;
    _context=context;
    try {
      _random=SecureRandom.getInstance("SHA1PRNG");
    }
 catch (    Exception e) {
      context.log("Could not get secure random for ID generation",e);
      _random=new Random();
    }
    _random.setSeed(_random.nextLong() ^ hashCode() ^ (context.hashCode() << 32)^ Runtime.getRuntime().freeMemory());
    _channelIdCache=new ConcurrentHashMap<String,ChannelId>();
    _root.addChild(new ServiceChannel(Bayeux.SERVICE));
  }
}
 

Example 111

From project remitt, under directory /src/main/java/org/remitt/server/.

Source file: PGPProvider.java

  15 
vote

/** 
 * @param data
 * @param encKey
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 */
public static byte[] encryptMessage(byte[] data,PGPPublicKey encKey) throws IOException, NoSuchProviderException, PGPException {
  boolean armor=true;
  boolean withIntegrityCheck=true;
  byte[] ret=null;
  OutputStream out=new ByteArrayOutputStream();
  if (armor) {
    out=new ArmoredOutputStream(out);
  }
  File tempfile=null;
  try {
    tempfile=File.createTempFile("pgp",null);
    FileUtils.writeByteArrayToFile(tempfile,data);
    ByteArrayOutputStream bOut=new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData=new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    PGPUtil.writeFileToLiteralData(comData.open(bOut),PGPLiteralData.BINARY,tempfile);
    comData.close();
    PGPEncryptedDataGenerator cPk=new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5,withIntegrityCheck,new SecureRandom(),"BC");
    cPk.addMethod(encKey);
    ret=bOut.toByteArray();
  }
 catch (  PGPException e) {
    log.error(e);
    if (e.getUnderlyingException() != null) {
      log.error(e.getUnderlyingException());
    }
    if (tempfile != null) {
      tempfile.delete();
    }
    throw e;
  }
 finally {
    if (tempfile != null) {
      tempfile.delete();
    }
  }
  return ret;
}