List of usage examples for java.security SecureRandom nextBytes
@Override public void nextBytes(byte[] bytes)
From source file:com.goodhustle.ouyaunitybridge.OuyaUnityActivity.java
public void requestPurchase(final String productId) throws GeneralSecurityException, UnsupportedEncodingException, JSONException { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); // This is an ID that allows you to associate a successful purchase with // it's original request. The server does nothing with this string except // pass it back to you, so it only needs to be unique within this instance // of your app to allow you to pair responses with requests. String uniqueId = Long.toHexString(sr.nextLong()); JSONObject purchaseRequest = new JSONObject(); purchaseRequest.put("uuid", uniqueId); purchaseRequest.put("identifier", productId); purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase String purchaseRequestJson = purchaseRequest.toString(); byte[] keyBytes = new byte[16]; sr.nextBytes(keyBytes); SecretKey key = new SecretKeySpec(keyBytes, "AES"); byte[] ivBytes = new byte[16]; sr.nextBytes(ivBytes);//from www. j av a2 s . c o m IvParameterSpec iv = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8")); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, mPublicKey); byte[] encryptedKey = cipher.doFinal(keyBytes); Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP), Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP)); synchronized (mOutstandingPurchaseRequests) { mOutstandingPurchaseRequests.put(uniqueId, productId); } ouyaFacade.requestPurchase(purchasable, new PurchaseListener(productId)); }
From source file:piuk.blockchain.android.WalletApplication.java
public void apiStoreKey(final String pin, final SuccessCallback callback) { final MyRemoteWallet blockchainWallet = this.blockchainWallet; if (blockchainWallet == null) { if (callback != null) callback.onFail();//from w ww. j a va 2s . c o m return; } final WalletApplication application = this; new Thread(new Runnable() { @Override public void run() { Looper.prepare(); Editor edit = PreferenceManager.getDefaultSharedPreferences(application).edit(); // // Save PIN // try { byte[] bytes = new byte[16]; SecureRandom random = new SecureRandom(); random.nextBytes(bytes); final String key = new String(Hex.encode(bytes), "UTF-8"); random.nextBytes(bytes); final String value = new String(Hex.encode(bytes), "UTF-8"); final JSONObject response = piuk.blockchain.android.ui.PinEntryActivity.apiStoreKey(key, value, pin); if (response.get("success") != null) { callback.onSuccess(); edit.putString("pin_kookup_key", key); edit.putString("encrypted_password", MyWallet.encrypt(application.getRemoteWallet().getTemporyPassword(), value, piuk.blockchain.android.ui.PinEntryActivity.PBKDF2Iterations)); if (!edit.commit()) { throw new Exception("Error Saving Preferences"); } else { } } else { Toast.makeText(application, response.toString(), Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(application, e.toString(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } // // // Looper.loop(); } }).start(); }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static void obscureBytes(byte[] memory, String method) { if (memory == null || memory.length == 0) { //in case we want to log return;/* w w w .j ava 2s.co m*/ } SecureRandom rnd; try { rnd = getRandomNumberGenerator(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } if ("zeroes".equals(method)) { Arrays.fill(memory, (byte) 0); } else { rnd.nextBytes(memory); } }
From source file:piuk.blockchain.android.MyRemoteWallet.java
private Pair<ECKey, String> generateNewMiniPrivateKey() { SecureRandom random = new SecureRandom(); while (true) { // Log.d("generateNewMiniPrivateKey", "generateNewMiniPrivateKey"); //Make Candidate Mini Key byte randomBytes[] = new byte[16]; random.nextBytes(randomBytes); String encodedBytes = Base58.encode(randomBytes); //TODO: Casascius Series 1 22-character variant, remember to notify Ben about updating to 30-character variant String minikey = 'S' + encodedBytes.substring(0, 21); try {/* w ww . j a va 2 s . c om*/ //Append ? & hash it again byte[] bytes_appended = MessageDigest.getInstance("SHA-256").digest((minikey + '?').getBytes()); //If zero byte then the key is valid if (bytes_appended[0] == 0) { try { //SHA256 byte[] bytes = MessageDigest.getInstance("SHA-256").digest(minikey.getBytes()); final ECKey eckey = new ECKey(bytes, null); final DumpedPrivateKey dumpedPrivateKey1 = eckey.getPrivateKeyEncoded(getParams()); String privateKey1 = Base58.encode(dumpedPrivateKey1.bytes); final String toAddress = eckey.toAddress(getParams()).toString(); /* Log.d("sendCoinsToFriend", "generateNewMiniPrivateKey: minikey: " + minikey); Log.d("sendCoinsToFriend", "generateNewMiniPrivateKey: privateKey: " + privateKey1); Log.d("sendCoinsToFriend", "generateNewMiniPrivateKey: address: " + toAddress); */ return new Pair<ECKey, String>(eckey, minikey); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:org.ejbca.util.CertTools.java
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/*from w ww .ja v a 2 s. c o m*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); certgen.setSerialNumber(new java.math.BigInteger(serno).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(publicKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey, provider); return selfcert; }
From source file:org.wso2.carbon.appmgt.impl.APIProviderImpl.java
private static String generateBinaryUUID() { SecureRandom secRandom = new SecureRandom(); byte[] result = new byte[8]; secRandom.nextBytes(result); String uuid = String.valueOf(Hex.encodeHex(result)); return uuid;/*from www .j ava 2 s .co m*/ }
From source file:org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager.java
/** * This private method returns a saltValue using SecureRandom. * * @return saltValue//ww w .ja va 2 s . c o m */ private String generateSaltValue() { String saltValue = null; try { SecureRandom secureRandom = SecureRandom.getInstance(UserCoreConstants.SHA_1_PRNG); byte[] bytes = new byte[16]; //secureRandom is automatically seeded by calling nextBytes secureRandom.nextBytes(bytes); saltValue = Base64.encode(bytes); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("SHA1PRNG algorithm could not be found."); } return saltValue; }
From source file:org.cesecore.util.CertTools.java
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder, List<Extension> additionalExtensions) throws CertificateParsingException, IOException, OperatorCreationException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;//from w ww. j a v a 2s. co m if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("RSA was not a known algorithm", e); } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" final String algo = ecpk.getAlgorithm(); if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { try { publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("ECGOST3410 was not a known algorithm", e); } } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { try { publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("DSTU4145 was not a known algorithm", e); } } else { try { publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("EC was not a known algorithm", e); } } } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA1PRNG was not a known algorithm", e); } random.setSeed(new Date().getTime()); random.nextBytes(serno); SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e); } X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA || keyusage != 0) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) { final ASN1EncodableVector v = new ASN1EncodableVector(); if (privateKeyNotBefore != null) { v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore))); } if (privateKeyNotAfter != null) { v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter))); } certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v)); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream sAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream aAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) sAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) aAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { sAsn1InputStream.close(); aAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } // Add any additional if (additionalExtensions != null) { for (final Extension extension : additionalExtensions) { certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue()); } } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:hudson.model.Hudson.java
public Hudson(File root, ServletContext context) throws IOException, InterruptedException { // As hudson is starting, grant this process full controll SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try {//from w w w . j a v a 2s . c om this.root = root; this.servletContext = context; computeVersion(context); if (theInstance != null) throw new IllegalStateException("second instance"); theInstance = this; log.load(); Trigger.timer = new Timer("Hudson cron thread"); queue = new Queue(CONSISTENT_HASH ? LoadBalancer.CONSISTENT_HASH : LoadBalancer.DEFAULT); try { dependencyGraph = DependencyGraph.EMPTY; } catch (InternalError e) { if (e.getMessage().contains("window server")) { throw new Error( "Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option", e); } throw e; } // get or create the secret TextFile secretFile = new TextFile(new File(Hudson.getInstance().getRootDir(), "secret.key")); if (secretFile.exists()) { secretKey = secretFile.readTrim(); } else { SecureRandom sr = new SecureRandom(); byte[] random = new byte[32]; sr.nextBytes(random); secretKey = Util.toHexString(random); secretFile.write(secretKey); } try { proxy = ProxyConfiguration.load(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Failed to load proxy configuration", e); } // load plugins. pluginManager = new PluginManager(context); pluginManager.initialize(); // if we are loading old data that doesn't have this field if (slaves == null) slaves = new NodeList(); adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader, "adjuncts/" + VERSION_HASH); load(); // try { // // fill up the cache // load(); // // Controller c = new Controller(); // c.startCPUProfiling(ProfilingModes.CPU_TRACING,""); // "java.*"); // load(); // c.stopCPUProfiling(); // c.captureSnapshot(ProfilingModes.SNAPSHOT_WITHOUT_HEAP); // } catch (Exception e) { // throw new Error(e); // } if (slaveAgentPort != -1) { try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } catch (BindException e) { new AdministrativeError(getClass().getName() + ".tcpBind", "Failed to listen to incoming slave connection", "Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.", e); } } else tcpSlaveAgentListener = null; udpBroadcastThread = new UDPBroadcastThread(this); udpBroadcastThread.start(); updateComputerList(); {// master is online now Computer c = toComputer(); if (c != null) for (ComputerListener cl : ComputerListener.all()) cl.onOnline(c, new StreamTaskListener(System.out)); } getQueue().load(); for (ItemListener l : ItemListener.all()) l.onLoaded(); // run the initialization script, if it exists. File initScript = new File(getRootDir(), "init.groovy"); if (initScript.exists()) { LOGGER.info("Executing " + initScript); GroovyShell shell = new GroovyShell(pluginManager.uberClassLoader); try { shell.evaluate(initScript); } catch (Throwable t) { t.printStackTrace(); } } File userContentDir = new File(getRootDir(), "userContent"); if (!userContentDir.exists()) { userContentDir.mkdirs(); FileUtils.writeStringToFile(new File(userContentDir, "readme.txt"), Messages.Hudson_USER_CONTENT_README()); } Trigger.init(); // start running trigger } finally { SecurityContextHolder.clearContext(); } }