private static byte[] key(final byte[] key) throws Exception {
   final KeyGenerator gen = KeyGenerator.getInstance(ALGORITHM);
   final SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
   sr.setSeed(key);
   gen.init(128, sr);
   return gen.generateKey().getEncoded();
 }
Exemplo n.º 2
0
 /**
  * Returns the SecureRandom used to generate secure random data.
  *
  * <p>Creates and initializes if null.
  *
  * @return the SecureRandom used to generate secure random data
  */
 private SecureRandom getSecRan() {
   if (secRand == null) {
     secRand = new SecureRandom();
     secRand.setSeed(System.currentTimeMillis());
   }
   return secRand;
 }
 // ---------------------------------------------------------------
 private byte[] getSalt(int saltSize) throws NoSuchAlgorithmException, NoSuchProviderException {
   // SecureRandom sr = SecureRandom.getInstance( SECURE_RANDOM_ALGORITHM,
   // SECURITY_PROVIDER );
   SecureRandom sr = new SecureRandom();
   sr.setSeed(System.currentTimeMillis());
   return sr.generateSeed(saltSize);
 }
Exemplo n.º 4
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap bm = null;
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
    byte[] b = baos.toByteArray();

    byte[] keyStart = "this is a key".getBytes();
    KeyGenerator kgen;
    try {
      kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(keyStart);
      kgen.init(128, sr); // 192 and 256 bits may not be available
      SecretKey skey = kgen.generateKey();
      byte[] key = skey.getEncoded();

      // encrypt
      byte[] encryptedData = encrypt(key, b);
      // decrypt
      byte[] decryptedData = decrypt(key, encryptedData);
    } catch (NoSuchAlgorithmException e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    } catch (Exception e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    }
  }
Exemplo n.º 5
0
  public boolean generateKeys() {

    PublicKey keyPub;
    PrivateKey keyPri;
    SecureRandom rand;

    Security.addProvider(new ABAProvider());

    rand = new SecureRandom();

    rand.setSeed(System.currentTimeMillis());

    try {
      KeyPairGenerator fact;
      KeyPair keyPair;

      fact = KeyPairGenerator.getInstance("RSA", "ABA");

      fact.initialize(1024, rand);

      keyPair = fact.generateKeyPair();

      keyPub = keyPair.getPublic();

      keyPri = keyPair.getPrivate();

      pubKey = bytesToHexStr(keyPub.getEncoded());

      priKey = bytesToHexStr(keyPri.getEncoded());
    } catch (Exception e) {
      return false;
    }
    return true;
  }
Exemplo n.º 6
0
  public PBEKeySpec getPassword(IPreferencesContainer container, int passwordType) {
    byte[] encryptedPassword;
    if ((passwordType & CREATE_NEW_PASSWORD) == 0)
      encryptedPassword = getEncryptedPassword(container);
    else encryptedPassword = null;

    if (encryptedPassword != null) {
      byte[] decryptedPassword = windecrypt(encryptedPassword);
      if (decryptedPassword != null) {
        String password = new String(decryptedPassword);
        return new PBEKeySpec(password.toCharArray());
      } else {
        StorageException e =
            new StorageException(
                StorageException.ENCRYPTION_ERROR, WinCryptoMessages.decryptPasswordFailed);
        AuthPlugin.getDefault().logError(WinCryptoMessages.decryptPasswordFailed, e);
        return null;
      }
    }

    // add info message in the log
    AuthPlugin.getDefault().logMessage(WinCryptoMessages.newPasswordGenerated);

    byte[] rawPassword = new byte[PASSWORD_LENGTH];
    SecureRandom random = new SecureRandom();
    random.setSeed(System.currentTimeMillis());
    random.nextBytes(rawPassword);
    String password = Base64.encode(rawPassword);
    if (savePassword(password, container)) return new PBEKeySpec(password.toCharArray());
    else return null;
  }
 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); // 192 and 256 bits may not be available
   return kgen.generateKey().getEncoded();
 }
Exemplo n.º 8
0
 /**
  * 产生任意给定长度的随纯机数字字符串。
  *
  * @param iLength 产生随机数的位数
  * @return 给定位数的随机数
  */
 public static String getRandomIntNum(int iLength) {
   sr.setSeed(System.currentTimeMillis());
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < iLength; i++) {
     sb.append(Math.abs(sr.nextInt(10)));
   }
   return sb.toString();
 }
Exemplo n.º 9
0
 /**
  * 获取RSA公私钥
  *
  * @param seedBytes
  * @return
  * @throws NoSuchAlgorithmException
  */
 public KeyPair generateRSAKeyPair(byte[] seedBytes) throws NoSuchAlgorithmException {
   KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
   int keySize = 1024; // 约定RSA加密采用1024位
   // linux下需强制设置RNG算法
   SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
   random.setSeed(seedBytes);
   keyGen.initialize(keySize, random);
   return keyGen.generateKeyPair();
 }
Exemplo n.º 10
0
 private byte[] getRawKey(byte[] seed) throws Exception {
   KeyGenerator kgen = KeyGenerator.getInstance("AES");
   SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
   sr.setSeed(seed);
   kgen.init(128, sr);
   SecretKey skey = kgen.generateKey();
   byte[] raw = skey.getEncoded();
   return raw;
 }
Exemplo n.º 11
0
 private byte[] getRawKey(byte[] seed) throws NoSuchAlgorithmException {
   KeyGenerator kgen = KeyGenerator.getInstance(PASS_ALGO);
   SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
   sr.setSeed(seed);
   kgen.init(128, sr);
   SecretKey skey = kgen.generateKey();
   byte[] raw = skey.getEncoded();
   return raw;
 }
 static void init(int numTerms) {
   SecureRandom random = new SecureRandom();
   random.setSeed(1);
   termsList.clear();
   for (int i = 0; i < numTerms; i++) {
     String term = new BigInteger(512, random).toString(32);
     termsList.add(term);
   }
 }
Exemplo n.º 13
0
  static {
    try {
      rnd = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
      rnd = new SecureRandom(); // Use default if prefered provider is unavailable
    }

    byte[] seed = rnd.generateSeed(64);
    rnd.setSeed(seed);
  }
Exemplo n.º 14
0
  // ZAP: added new ServerSocketFaktory with support of dynamic SSL certificates
  public SSLSocketFactory getTunnelSSLSocketFactory(String hostname) {

    //	SSLServerSocketFactory ssf = null;
    // set up key manager to do server authentication

    //	KeyStore ks;
    try {
      SSLContext ctx = SSLContext.getInstance("SSL");
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

      SslCertificateService scs = CachedSslCertifificateServiceImpl.getService();
      KeyStore ks = scs.createCertForHost(hostname);

      kmf.init(ks, SslCertificateService.PASSPHRASE);
      java.security.SecureRandom x = new java.security.SecureRandom();
      x.setSeed(System.currentTimeMillis());
      ctx.init(kmf.getKeyManagers(), null, x);

      SSLSocketFactory tunnelSSLFactory = ctx.getSocketFactory();

      return tunnelSSLFactory;

    } catch (NoSuchAlgorithmException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    } catch (KeyStoreException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    } catch (CertificateException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
      //	} catch (IOException e) {
      //		// Turn into RuntimeException. How to handle this error in a user friendly way?
      //		throw new RuntimeException(e);
    } catch (UnrecoverableKeyException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    } catch (KeyManagementException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    } catch (NoSuchProviderException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    } catch (SignatureException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    } catch (IOException e) {
      // Turn into RuntimeException. How to handle this error in a user friendly way?
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 15
0
 public static void setKey(String key) {
   try {
     KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_AES);
     SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM_SHA1_PRNG);
     secureRandom.setSeed(key.getBytes());
     keyGenerator.init(secureRandom);
     setAesKey(keyGenerator.generateKey());
     keyGenerator = null;
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 private SecureRandom createSecureRandom(String algorithm, String provider, int keyLength) {
   try {
     SecureRandom random = SecureRandom.getInstance(algorithm, provider);
     random.setSeed(random.generateSeed(keyLength));
     return random;
   } catch (NoSuchAlgorithmException e) {
     throw new IllegalArgumentException(
         "Not a supported SecureRandom key generation algorithm", e);
   } catch (NoSuchProviderException e) {
     throw new IllegalArgumentException("Not a supported SecureRandom key provider", e);
   }
 }
Exemplo n.º 17
0
 public String generateToken(String userName) throws PhrescoException {
   String token = "";
   try {
     SecureRandom random = SecureRandom.getInstance(ALGORITHM_NAME);
     byte[] seed = random.generateSeed(132);
     random.setSeed(seed);
     token = new BigInteger(132, random).toString(32);
     tokenCache.put(token, userName);
   } catch (NoSuchAlgorithmException e) {
     throw new PhrescoException(e);
   }
   return token;
 }
Exemplo n.º 18
0
  public void testLIFO() {

    SecureRandom sr = new SecureRandom();
    sr.setSeed(System.currentTimeMillis());

    int ntries = 1;

    for (int i = 0; i < ntries; i++) {

      int n = 1000;

      float[] x = createRandomNumbers(sr, n);
      float[] y = createRandomNumbers(sr, n);

      XYStack stack = new XYStack();

      for (int j = 0; j < n; j++) {
        stack.push(x[j], y[j]);
      }

      float xCheck0 = x[n - 1];
      float yCheck0 = y[n - 1];

      float xCheck1 = x[n - 2];
      float yCheck1 = y[n - 2];

      float xCheck2 = x[n - 3];
      float yCheck2 = y[n - 3];

      float xCheck3 = x[n - 4];
      float yCheck3 = y[n - 4];

      float[] result0 = stack.pop();
      float[] result1 = stack.pop();
      float[] result2 = stack.pop();
      float[] result3 = stack.pop();

      assertTrue(Math.abs(xCheck0 - result0[0]) < 0.01);
      assertTrue(Math.abs(yCheck0 - result0[1]) < 0.01);

      assertTrue(Math.abs(xCheck1 - result1[0]) < 0.01);
      assertTrue(Math.abs(yCheck1 - result1[1]) < 0.01);

      assertTrue(Math.abs(xCheck2 - result2[0]) < 0.01);
      assertTrue(Math.abs(yCheck2 - result2[1]) < 0.01);

      assertTrue(Math.abs(xCheck3 - result3[0]) < 0.01);
      assertTrue(Math.abs(yCheck3 - result3[1]) < 0.01);
    }
  }
  public static String buildNonce(Date date) {
    String nonce = "";
    try {
      SecureRandom random = java.security.SecureRandom.getInstance("SHA1PRNG");
      random.setSeed(date.getTime());
      byte[] nonceBytes = new byte[16];
      random.nextBytes(nonceBytes);
      nonce = new String(Base64.encodeBase64(nonceBytes), "UTF-8");

    } catch (Exception e) {
      e.printStackTrace();
    }
    return nonce;
  }
Exemplo n.º 20
0
  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;
  }
Exemplo n.º 21
0
 private static byte[] getRawKey(byte[] seed) throws Exception {
   KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
   // SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法
   SecureRandom sr = null;
   if (android.os.Build.VERSION.SDK_INT >= 17) {
     sr = SecureRandom.getInstance("SHA1PRNG", PROVIDER);
   } else {
     sr = SecureRandom.getInstance("SHA1PRNG");
   }
   sr.setSeed(seed);
   kgen.init(KEY_SIZE, sr); // 256 bits or 128 bits,192bits
   SecretKey skey = kgen.generateKey();
   byte[] raw = skey.getEncoded();
   return raw;
 }
Exemplo n.º 22
0
 public Long getChallenge() {
   if (challenge == null) {
     SecureRandom random;
     try {
       random = SecureRandom.getInstance("SHA1PRNG", "SUN");
     } catch (NoSuchAlgorithmException ex) {
       random = new SecureRandom();
       LOGGER.error(ex.getMessage(), ex);
     } catch (NoSuchProviderException ex) {
       random = new SecureRandom();
       LOGGER.error(ex.getMessage(), ex);
     }
     random.setSeed((new Date()).getTime());
     challenge = random.nextLong() % (10 ^ 6);
   }
   return challenge;
 }
Exemplo n.º 23
0
 public static String decrypt(byte[] content, String keyWord) throws OfficeException {
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
     secureRandom.setSeed(keyWord.getBytes());
     kgen.init(128, secureRandom);
     SecretKey secretKey = kgen.generateKey();
     byte[] enCodeFormat = secretKey.getEncoded();
     SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
     Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.DECRYPT_MODE, key);
     byte[] result = cipher.doFinal(content);
     return new String(result);
   } catch (Exception e) {
     throw new OfficeException("encrypt failed:", e);
   }
 }
Exemplo n.º 24
0
 /*
  * 获得AES密钥
  */
 byte[] generateAesByte(byte[] seedBytes) {
   // AIX小型机下SecureRandom算法不一致
   KeyGenerator keyGen = null;
   int keySize = 128; // 约定AES加密采用 128 位
   // linux下需强制设置RNG算法
   SecureRandom random = null;
   try {
     keyGen = KeyGenerator.getInstance("AES");
     random = SecureRandom.getInstance("SHA1PRNG");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
   random.setSeed(seedBytes);
   keyGen.init(keySize, random);
   SecretKey secretKey = keyGen.generateKey();
   return secretKey.getEncoded();
 }
Exemplo n.º 25
0
  private Tetromino createRandomTetromino() {
    Tetromino result = null;

    SecureRandom random = new SecureRandom();

    random.setSeed(UUID.randomUUID().hashCode());

    int type = random.nextInt(NUMBER_OF_TETROMINO_TYPE);
    switch (type) {
      case TETROMINO_L:
        result = new LTetromino();
        break;
      case TETROMINO_J:
        result = new JTetromino();
        break;
      case TETROMINO_S:
        result = new STetromino();
        break;
      case TETROMINO_Z:
        result = new ZTetromino();
        break;
      case TETROMINO_T:
        result = new TTetromino();
        break;
      case TETROMINO_O:
        result = new OTetromino();
        break;
      case TETROMINO_I:
        result = new ITetromino();
        break;
    }

    int color = random.nextInt(Tetromino.NUMBER_OF_COLOR) + 1;
    result.setColor(color);
    result.setX(0);
    result.setY(0);

    int col = result.getFirstBlockColIndex();
    int row = result.getFirstBlockRowIndex();

    result.setX(4 - col);
    result.setY(0 - row);

    return result;
  }
  public Client createClient(
      PackageInfoOAuth packageInfo,
      ClientType clientType,
      String[] redirectURIs,
      Map<String, Object> properties) {
    if (properties == null) {
      properties = new HashMap<String, Object>();
    }

    Object flows = properties.get(Client.PROPERTY_SUPPORTED_FLOWS);
    if (flows == null) {
      flows = defaultSupportedFlow.get(clientType);
      properties.put(Client.PROPERTY_SUPPORTED_FLOWS, flows);
    }

    /*
     * The authorization server MUST require the following clients to
     * register their redirection endpoint: o Public clients. o Confidential
     * clients utilizing the implicit grant type. (3.1.2.2. Registration
     * Requirements)
     */
    if (clientType == ClientType.PUBLIC
        || (clientType == ClientType.CONFIDENTIAL
            && Arrays.asList((Object[]) flows).contains(ResponseType.token))) {
      if (redirectURIs == null || redirectURIs.length == 0) {
        throw new IllegalArgumentException("RedirectionURI(s) required.");
      }
    }

    String clientId = UUID.randomUUID().toString();
    char[] clientSecret = null;
    if (clientType == ClientType.CONFIDENTIAL
        || (clientType == ClientType.PUBLIC && isIssueClientSecretToPublicClients())) {
      // Issue a client secret to the confidential client.
      if (count++ > RESEED_CLIENTS) {
        count = 0;
        random.setSeed(random.generateSeed(20));
      }
      byte[] secret = new byte[20];
      random.nextBytes(secret);
      clientSecret = Base64.encode(secret, false).toCharArray();
    }

    return createClient(packageInfo, clientId, clientSecret, clientType, redirectURIs, properties);
  }
Exemplo n.º 27
0
  public SSLSocketFactory getClientSocketFactory(String type) {
    // Trust all invalid server certificate
    TrustManager[] trustMgr = new TrustManager[] {new RelaxedX509TrustManager()};

    try {
      SSLContext sslContext = SSLContext.getInstance(type);
      java.security.SecureRandom x = new java.security.SecureRandom();
      x.setSeed(System.currentTimeMillis());
      sslContext.init(null, trustMgr, x);
      clientSSLSockFactory = sslContext.getSocketFactory();
      HttpsURLConnection.setDefaultSSLSocketFactory(clientSSLSockFactory);

    } catch (Exception e) {
      e.printStackTrace();
    }

    return clientSSLSockFactory;
  }
 /** Safely initializes the random number generator, by seeding it with data from /dev/urandom. */
 public static void initialize(SecureRandom generator) throws IOException {
   FileInputStream fis = null;
   try {
     fis = new FileInputStream("/dev/urandom");
     if (fis.read(sSeedBytes) != sSeedBytes.length) {
       throw new IOException("Failed to get enough random data.");
     }
     generator.setSeed(sSeedBytes);
   } finally {
     try {
       if (fis != null) {
         fis.close();
       }
     } catch (IOException e) {
       // Ignore exception closing the device.
     }
   }
 }
Exemplo n.º 29
0
 public AESEncryptor(String key) {
   KeyGenerator generator = null;
   try {
     generator = KeyGenerator.getInstance("AES");
     SecureRandom secureRandom;
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
       secureRandom = SecureRandom.getInstance("SHA1PRNG", "Crypto");
     } else {
       secureRandom = SecureRandom.getInstance("SHA1PRNG");
     }
     secureRandom.setSeed(key.getBytes());
     generator.init(128, secureRandom);
   } catch (Exception e) {
     Log.e(TAG, e.getMessage());
   }
   if (generator != null) {
     mKeyBytes = generator.generateKey().getEncoded();
   }
 }
Exemplo n.º 30
0
  /** Creates a new instance of Encrypter */
  public AltEncrypter(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();

      cipherEncrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
      cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);

      cipherDecrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
      cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
    } catch (UnsupportedEncodingException e) {
    } catch (NoSuchPaddingException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidKeyException e) {
    }
  }