{ try { rng = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw (new Error(e)); } }
// Generate Random Key static Key makeKey(int keyBit) throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance("AES"); SecureRandom rd = SecureRandom.getInstance("SHA1PRNG"); kg.init(keyBit, rd); Key key = kg.generateKey(); return key; } // makeKey
public void generate_new_aes_key() { try { KeyGenerator localKeyGenerator = KeyGenerator.getInstance("AES"); localKeyGenerator.init(128, SecureRandom.getInstance("SHA1PRNG")); // aes_key = Base64.encodeBase64String(localKeyGenerator.generateKey().getEncoded()); aes_key = new String(Base64.encode(localKeyGenerator.generateKey().getEncoded(), Base64.DEFAULT)); } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) { System.out.println(localNoSuchAlgorithmException); } return; }
/** 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) { } }
/** * Encrypts the given input data. * * @param in input data to encrypt * @param k key * @param a encryption algorithm * @param ivl initialization vector length * @return encrypted input data * @throws InvalidKeyException ex * @throws InvalidAlgorithmParameterException ex * @throws NoSuchAlgorithmException ex * @throws NoSuchPaddingException ex * @throws IllegalBlockSizeException ex * @throws BadPaddingException ex */ private static byte[] encrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a)))); final SecretKeySpec kspec = new SecretKeySpec(k, string(a)); // generate random iv. random iv is necessary to make the encryption of a // string look different every time it is encrypted. final byte[] iv = new byte[ivl]; // create new random iv if encrypting final SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); rand.nextBytes(iv); final IvParameterSpec ivspec = new IvParameterSpec(iv); // encrypt/decrypt cipher.init(Cipher.ENCRYPT_MODE, kspec, ivspec); final byte[] t = cipher.doFinal(in); // initialization vector is appended to the message for later decryption return concat(iv, t); }
/** * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the default. Does nothing * if the implementation is already the default or if there is not need to install the * implementation. * * @throws SecurityException if the fix is needed but could not be applied. */ private static void installLinuxPRNGSecureRandom() throws SecurityException { if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) { // No need to apply the fix return; } // Install a Linux PRNG-based SecureRandom implementation as the // default, if not yet installed. Provider[] secureRandomProviders = Security.getProviders("SecureRandom.SHA1PRNG"); if ((secureRandomProviders == null) || (secureRandomProviders.length < 1) || (!LinuxPRNGSecureRandomProvider.class.equals(secureRandomProviders[0].getClass()))) { Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1); } // Assert that new SecureRandom() and // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed // by the Linux PRNG-based SecureRandom implementation. SecureRandom rng1 = new SecureRandom(); if (!LinuxPRNGSecureRandomProvider.class.equals(rng1.getProvider().getClass())) { throw new SecurityException( "new SecureRandom() backed by wrong Provider: " + rng1.getProvider().getClass()); } SecureRandom rng2; try { rng2 = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new SecurityException("SHA1PRNG not available", e); } if (!LinuxPRNGSecureRandomProvider.class.equals(rng2.getProvider().getClass())) { throw new SecurityException( "SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong" + " Provider: " + rng2.getProvider().getClass()); } }
public static void main(String[] args) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); byte[] encPriv = priv.getEncoded(); FileOutputStream privfos = new FileOutputStream("DSAPrivateKey.key"); privfos.write(encPriv); privfos.close(); byte[] encPub = pub.getEncoded(); FileOutputStream pubfos = new FileOutputStream("DSAPublicKey.key"); pubfos.write(encPub); pubfos.close(); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { // Dynamically register the SunMSCAPI provider Security.addProvider(new sun.security.mscapi.SunMSCAPI()); Provider p = Security.getProvider("SunMSCAPI"); System.out.println("SunMSCAPI provider classname is " + p.getClass().getName()); System.out.println("SunMSCAPI provider name is " + p.getName()); System.out.println("SunMSCAPI provider version # is " + p.getVersion()); System.out.println("SunMSCAPI provider info is " + p.getInfo()); /* * Secure Random */ SecureRandom random = SecureRandom.getInstance("Windows-PRNG", p); System.out.println(" Windows-PRNG is implemented by: " + random.getClass().getName()); /* * Key Store */ KeyStore keystore = KeyStore.getInstance("Windows-MY", p); System.out.println(" Windows-MY is implemented by: " + keystore.getClass().getName()); keystore = KeyStore.getInstance("Windows-ROOT", p); System.out.println(" Windows-ROOT is implemented by: " + keystore.getClass().getName()); /* * Signature */ Signature signature = Signature.getInstance("SHA1withRSA", p); System.out.println(" SHA1withRSA is implemented by: " + signature.getClass().getName()); signature = Signature.getInstance("MD5withRSA", p); System.out.println(" MD5withRSA is implemented by: " + signature.getClass().getName()); signature = Signature.getInstance("MD2withRSA", p); System.out.println(" MD2withRSA is implemented by: " + signature.getClass().getName()); /* * Key Pair Generator */ KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA", p); System.out.println(" RSA is implemented by: " + keypairGenerator.getClass().getName()); /* * Cipher */ Cipher cipher = null; try { cipher = Cipher.getInstance("RSA", p); System.out.println(" RSA is implemented by: " + cipher.getClass().getName()); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", p); System.out.println( " RSA/ECB/PKCS1Padding is implemented by: " + cipher.getClass().getName()); } catch (GeneralSecurityException e) { System.out.println("Cipher not supported by provider, skipping..."); } }
public static void load(Properties properties) throws NoSuchAlgorithmException, InstantiationException, IllegalAccessException, ClassNotFoundException, IOException, NoSuchProviderException { CsrfGuard csrfGuard = SingletonHolder.instance; /** load simple properties * */ csrfGuard.setLogger( (ILogger) Class.forName( properties.getProperty( "org.owasp.csrfguard.Logger", "org.owasp.csrfguard.log.ConsoleLogger")) .newInstance()); csrfGuard.setTokenName( properties.getProperty("org.owasp.csrfguard.TokenName", "OWASP_CSRFGUARD")); csrfGuard.setTokenLength( Integer.parseInt(properties.getProperty("org.owasp.csrfguard.TokenLength", "32"))); csrfGuard.setRotate( Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Rotate", "false"))); csrfGuard.setTokenPerPage( Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.TokenPerPage", "false"))); csrfGuard.setTokenPerPagePrecreate( Boolean.valueOf( properties.getProperty("org.owasp.csrfguard.TokenPerPagePrecreate", "false"))); csrfGuard.setPrng( SecureRandom.getInstance( properties.getProperty("org.owasp.csrfguard.PRNG", "SHA1PRNG"), properties.getProperty("org.owasp.csrfguard.PRNG.Provider", "SUN"))); csrfGuard.setNewTokenLandingPage( properties.getProperty("org.owasp.csrfguard.NewTokenLandingPage")); // default to false if newTokenLandingPage is not set; default to true if set. if (csrfGuard.getNewTokenLandingPage() == null) { csrfGuard.setUseNewTokenLandingPage( Boolean.valueOf( properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "false"))); } else { csrfGuard.setUseNewTokenLandingPage( Boolean.valueOf( properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "true"))); } csrfGuard.setSessionKey( properties.getProperty("org.owasp.csrfguard.SessionKey", "OWASP_CSRFGUARD_KEY")); csrfGuard.setAjax(Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Ajax", "false"))); csrfGuard.setProtect( Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Protect", "false"))); /** first pass: instantiate actions * */ Map<String, IAction> actionsMap = new HashMap<String, IAction>(); for (Object obj : properties.keySet()) { String key = (String) obj; if (key.startsWith(ACTION_PREFIX)) { String directive = key.substring(ACTION_PREFIX.length()); int index = directive.indexOf('.'); /** action name/class * */ if (index < 0) { String actionClass = properties.getProperty(key); IAction action = (IAction) Class.forName(actionClass).newInstance(); action.setName(directive); actionsMap.put(action.getName(), action); csrfGuard.getActions().add(action); } } } /** second pass: initialize action parameters * */ for (Object obj : properties.keySet()) { String key = (String) obj; if (key.startsWith(ACTION_PREFIX)) { String directive = key.substring(ACTION_PREFIX.length()); int index = directive.indexOf('.'); /** action name/class * */ if (index >= 0) { String actionName = directive.substring(0, index); IAction action = actionsMap.get(actionName); if (action == null) { throw new IOException( String.format("action class %s has not yet been specified", actionName)); } String parameterName = directive.substring(index + 1); String parameterValue = properties.getProperty(key); action.setParameter(parameterName, parameterValue); } } } /** ensure at least one action was defined * */ if (csrfGuard.getActions().size() <= 0) { throw new IOException("failure to define at least one action"); } /** initialize protected, unprotected pages * */ for (Object obj : properties.keySet()) { String key = (String) obj; if (key.startsWith(PROTECTED_PAGE_PREFIX)) { String directive = key.substring(PROTECTED_PAGE_PREFIX.length()); int index = directive.indexOf('.'); /** page name/class * */ if (index < 0) { String pageUri = properties.getProperty(key); csrfGuard.getProtectedPages().add(Pattern.compile(pageUri)); } } if (key.startsWith(UNPROTECTED_PAGE_PREFIX)) { String directive = key.substring(UNPROTECTED_PAGE_PREFIX.length()); int index = directive.indexOf('.'); /** page name/class * */ if (index < 0) { String pageUri = properties.getProperty(key); csrfGuard.getUnprotectedPages().add(Pattern.compile(pageUri)); } } } /** initialize protected methods * */ String methodList = properties.getProperty("org.owasp.csrfguard.ProtectedMethods"); if (methodList != null && methodList.trim().length() != 0) { for (String method : methodList.split(",")) { csrfGuard.getProtectedMethods().add(method.trim()); } } }
public double runTest(String exec, String seed) { try { this.exec = exec; readFiles(); Random r; try { r = SecureRandom.getInstance("SHA1PRNG"); r.setSeed(Long.parseLong(seed)); } catch (Exception e) { return -1; } P = r.nextDouble() * 0.04 + 0.01; C = r.nextDouble() * 1e-3; String[] medkit = getMedkit(availableResources, requiredResources, missions, P, C); if (medkit == null) { System.err.println("Got null"); return 0; } double[] mk = new double[10000]; for (int i = 0; i < medkit.length; i++) { String[] sp = medkit[i].split(" "); if (sp.length != 2) { System.err.println("Invalid return. Element not formatted correctly: " + medkit[i]); return 0; } try { int rid = Integer.parseInt(sp[0].substring(1)); double cnt = Double.parseDouble(sp[1]); if (cnt < 0 || Double.isNaN(cnt) || Double.isInfinite(cnt)) { System.err.println("Your return contained an invalid double"); return 0; } mk[rid] += cnt; } catch (Exception e) { System.err.println("Invalid return. Element not formatted correctly: " + medkit[i]); return 0; } } String[] sample = missions; int[] used = new int[100000]; ArrayList<String[]> al[] = new ArrayList[10000]; Arrays.fill(used, -1); for (int i = 0; i < 10000; i++) { al[i] = new ArrayList(); int j = r.nextInt(used.length); while (used[j] != -1) { j = r.nextInt(used.length); } used[j] = i; } for (int i = 0; i < sample.length; i++) { String[] sp = sample[i].split(" "); int mid = Integer.parseInt(sp[0]); if (used[mid - 1] != -1) { al[used[mid - 1]].add(sp); } } int evac = 0; for (int i = 0; i < 10000; i++) { double[] m = (double[]) mk.clone(); evac += eval(m, al[i]); } System.err.println("Total evacuations: " + evac + "\n"); if (evac <= P * 10000) { double score = 0; double m = 0, v = 0; for (int i = 0; i < mk.length; i++) { m += mass[i] * mk[i]; v += vol[i] * mk[i]; } score = C * v + m; System.out.println("Total mass: " + m + "\n"); System.out.println("Total volume: " + v + "\n"); return 1000 / score; } else { System.out.println("Evacutions exceeded allowed rate"); return 0; } } catch (Exception e) { System.err.println(e.toString() + "\n"); StackTraceElement[] ste = e.getStackTrace(); for (int i = 0; i < ste.length; i++) System.err.println(ste[i] + "\n"); return -1; } }