private static byte[] calculatePbeMac( DERObjectIdentifier oid, byte[] salt, int itCount, char[] password, byte[] data, String provider) throws Exception { SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), provider); PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); PBEKeySpec pbeSpec = new PBEKeySpec(password); SecretKey key = keyFact.generateSecret(pbeSpec); Mac mac = Mac.getInstance(oid.getId(), provider); mac.init(key, defParams); mac.update(data); return mac.doFinal(); }
protected Cipher makePBECipher( String algorithm, int mode, char[] password, byte[] salt, int iterationCount) throws IOException { try { PBEKeySpec pbeSpec = new PBEKeySpec(password); SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME); PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount); Cipher cipher = Cipher.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME); cipher.init(mode, keyFact.generateSecret(pbeSpec), defParams); return cipher; } catch (Exception e) { throw new IOException("Error initialising store of key store: " + e); } }
private static byte[] calculatePbeMac( ASN1ObjectIdentifier oid, byte[] salt, int itCount, char[] password, boolean wrongPkcs12Zero, byte[] data) throws Exception { SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), bcProvider); PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); PBEKeySpec pbeSpec = new PBEKeySpec(password); BCPBEKey key = (BCPBEKey)keyFact.generateSecret(pbeSpec); key.setTryWrongPKCS12Zero(wrongPkcs12Zero); Mac mac = Mac.getInstance(oid.getId(), bcProvider); mac.init(key, defParams); mac.update(data); return mac.doFinal(); }
private AlgorithmParameters getAlgorithmParameters(String algorithm) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), iterationCount); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); } catch (Exception e) { throw new IOException("getAlgorithmParameters failed: " + e.getMessage(), e); } return algParams; }
private void setUp() { out.println("Using KEYSTORE_PATH:"+KEYSTORE_PATH); Utils.createKeyStore(Utils.KeyStoreType.pkcs12, KEYSTORE_PATH, ALIAS); Random rand = RandomFactory.getRandom(); rand.nextBytes(SALT); out.print("Salt: "); for (byte b : SALT) { out.format("%02X ", b); } out.println(""); PASSWORD_PROTECTION .add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithMD5AndDES", new PBEParameterSpec(SALT, ITERATION_COUNT))); PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndDESede", null)); PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC2_40", null)); PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC2_128", null)); PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC4_40", null)); PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC4_128", null)); }
private static Cipher getCipherFromPassphrase(String passphrase, byte[] salt, int iterations, int opMode) throws GeneralSecurityException { SecretKey key = getKeyFromPassphrase(passphrase, salt, iterations); Cipher cipher = Cipher.getInstance(key.getAlgorithm()); cipher.init(opMode, key, new PBEParameterSpec(salt, iterations)); return cipher; }
public static String encriptar(String passPhrase, String str) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { Cipher ecipher = null; Cipher dcipher = null; java.security.spec.KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT_BYTES, ITERATION_COUNT); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); java.security.spec.AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT_BYTES, ITERATION_COUNT); ecipher.init(1, key, paramSpec); dcipher.init(2, key, paramSpec); byte utf8[] = str.getBytes("UTF8"); byte enc[] = ecipher.doFinal(utf8); return (new BASE64Encoder()).encode(enc); }
public static String desencriptar(String passPhrase, String str) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException { Cipher ecipher = null; Cipher dcipher = null; java.security.spec.KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT_BYTES, ITERATION_COUNT); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); java.security.spec.AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT_BYTES, ITERATION_COUNT); ecipher.init(1, key, paramSpec); dcipher.init(2, key, paramSpec); byte dec[] = (new BASE64Decoder()).decodeBuffer(str); byte utf8[] = dcipher.doFinal(dec); return new String(utf8, "UTF8"); }
/** * 加密明文字符串 * * @param plaintext * 待加密的明文字符串 * @param password * 生成密钥时所使用的密码 * @param salt * 盐值 * @return 加密后的密文字符串 * @throws Exception */ public static String encrypt(String plaintext, String password, byte[] salt) { Key key = getPBEKey(password); byte[] encipheredData = null; PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, ITERATIONCOUNT); try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec); encipheredData = cipher.doFinal(plaintext.getBytes()); } catch (Exception e) { } return bytesToHexString(encipheredData); }
/** * 解密密文字符串 * * @param ciphertext * 待解密的密文字符串 * @param password * 生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致) * @param salt * 盐值(如需解密,该参数需要与加密时使用的一致) * @return 解密后的明文字符串 * @throws Exception */ public static String decrypt(String ciphertext, String password, byte[] salt) { Key key = getPBEKey(password); byte[] passDec = null; PBEParameterSpec parameterSpec = new PBEParameterSpec(getStaticSalt(), ITERATIONCOUNT); try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec); passDec = cipher.doFinal(hexStringToBytes(ciphertext)); } catch (Exception e) { // TODO: handle exception } return new String(passDec); }
/** * Builds the java cipher using the BouncyCastle crypto library) * * @param encryptMode Cipher.DECRYPT_MODE or Cipher.ENCRYPT_MODE * @return the AES256 encrypt or decrypt cipher * @throws InvalidKeySpecException if the key specification is invalid * @throws InvalidAlgorithmParameterException if the algorithm is not supported * @throws InvalidKeyException if the key is invalid * @throws NoSuchAlgorithmException if the encryption system fails * @throws NoSuchPaddingException if the algorithm padding parameter is not supported */ private static Cipher buildCipher(int encryptMode) throws InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { //Create the key specification PBEParameterSpec pbeParamSpec = new PBEParameterSpec(ENCRYPTION_SALT, ENCRYPTION_ITERATION_COUNT); PBEKeySpec pbeKeySpec = new PBEKeySpec(ENCRYPTION_PASSPHRASE); //Configure the key SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM); SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec); //Initialise the cipher Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); cipher.init(encryptMode, secretKey, pbeParamSpec); return cipher; }
private AlgorithmParameters getPBEAlgorithmParameters(String algorithm) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), PBE_ITERATION_COUNT); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); } catch (Exception e) { throw new IOException("getPBEAlgorithmParameters failed: " + e.getMessage(), e); } return algParams; }
private static byte[] calculatePbeMac( ASN1ObjectIdentifier oid, byte[] salt, int itCount, char[] password, byte[] data, String provider) throws Exception { SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), provider); PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); PBEKeySpec pbeSpec = new PBEKeySpec(password); SecretKey key = keyFact.generateSecret(pbeSpec); Mac mac = Mac.getInstance(oid.getId(), provider); mac.init(key, defParams); mac.update(data); return mac.doFinal(); }
/** * generate a PBE based key suitable for a MAC algorithm, the * key size is chosen according the MAC size, or the hashing algorithm, * whichever is greater. */ public static CipherParameters makePBEMacParameters( BCPBEKey pbeKey, AlgorithmParameterSpec spec) { if ((spec == null) || !(spec instanceof PBEParameterSpec)) { throw new IllegalArgumentException("Need a PBEParameter spec with a PBE key."); } PBEParameterSpec pbeParam = (PBEParameterSpec)spec; PBEParametersGenerator generator = makePBEGenerator(pbeKey.getType(), pbeKey.getDigest()); byte[] key = pbeKey.getEncoded(); CipherParameters param; generator.init(key, pbeParam.getSalt(), pbeParam.getIterationCount()); param = generator.generateDerivedMacParameters(pbeKey.getKeySize()); for (int i = 0; i != key.length; i++) { key[i] = 0; } return param; }
/** * generate a PBE based key suitable for a MAC algorithm, the * key size is chosen according the MAC size, or the hashing algorithm, * whichever is greater. */ public static CipherParameters makePBEMacParameters( SecretKey key, int type, int hash, int keySize, PBEParameterSpec pbeSpec) { PBEParametersGenerator generator = makePBEGenerator(type, hash); CipherParameters param; byte[] keyBytes = key.getEncoded(); generator.init(key.getEncoded(), pbeSpec.getSalt(), pbeSpec.getIterationCount()); param = generator.generateDerivedMacParameters(keySize); for (int i = 0; i != keyBytes.length; i++) { keyBytes[i] = 0; } return param; }
protected Cipher makePBECipher( String algorithm, int mode, char[] password, byte[] salt, int iterationCount) throws IOException { try { PBEKeySpec pbeSpec = new PBEKeySpec(password); SecretKeyFactory keyFact = helper.createSecretKeyFactory(algorithm); PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount); Cipher cipher = helper.createCipher(algorithm); cipher.init(mode, keyFact.generateSecret(pbeSpec), defParams); return cipher; } catch (Exception e) { throw new IOException("Error initialising store of key store: " + e); } }
private byte[] calculatePbeMac( ASN1ObjectIdentifier oid, byte[] salt, int itCount, char[] password, boolean wrongPkcs12Zero, byte[] data) throws Exception { PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); Mac mac = helper.createMac(oid.getId()); mac.init(new PKCS12Key(password, wrongPkcs12Zero), defParams); mac.update(data); return mac.doFinal(); }
/** * Use this encryption when the values should be used only inside the scope of the application, since it depends on the device. * For example - use when a value needs to be scrambled before it's saved to the preferences, and decrypted when read from there. */ public String encrypt(Context context, String value) { if (value == null){ return null; } try { final byte[] bytes = value.getBytes(UTF8); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(mSerkit)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec( Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes(UTF8), 20)); return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8); } catch (Exception e) { throw new RuntimeException(e); } }
public String decrypt(Context context, String value) { if (value == null){ return null; } try { final byte[] bytes = Base64.decode(value, Base64.DEFAULT); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(mSerkit)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec( Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20)); return new String(pbeCipher.doFinal(bytes),UTF8); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Method to encrypt the data * * @param input Data to be encrypted * @return Encrypted data * @throws OpenStegoException */ public byte[] encrypt(byte[] input) throws OpenStegoException { try { Cipher encryptCipher = Cipher.getInstance(this.secretKey.getAlgorithm()); AlgorithmParameterSpec algoParamSpec = new PBEParameterSpec(this.SALT, this.ITER_COUNT); encryptCipher.init(Cipher.ENCRYPT_MODE, this.secretKey, algoParamSpec); byte[] algoParams = encryptCipher.getParameters().getEncoded(); byte[] msg = encryptCipher.doFinal(input); byte paramLen = Byte.parseByte(Integer.toString(algoParams.length)); byte[] out = new byte[1 + paramLen + msg.length]; // First byte = length of algo params out[0] = paramLen; // Next is algorithm params System.arraycopy(algoParams, 0, out, 1, paramLen); // Next is encrypted message System.arraycopy(msg, 0, out, paramLen + 1, msg.length); return out; } catch (Exception ex) { throw new OpenStegoException(ex); } }
public static Cipher buildEncryptor(char[] pw, byte[] salt) { try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm); KeySpec pbeKeySpec = new PBEKeySpec(pw, salt, iterations, pw.length); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); PBEParameterSpec paramSpec = new PBEParameterSpec(salt, iterations); Cipher enc = Cipher.getInstance(algorithm); enc.init(Cipher.ENCRYPT_MODE, pbeKey, paramSpec); return enc; } catch (Exception e) { e.printStackTrace(System.err); return null; } }
protected void saveCipheredStock() { try { JSONObject json = new JSONObject(); for (String pid: mStock.keySet()) { json.put(pid, mStock.get(pid)); } final byte[] bytes = json.toString().getBytes("utf-8"); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(getUniquePseudoID().toCharArray())); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(mContext.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes("utf-8"), 20)); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); SharedPreferences.Editor editor = preferences.edit(); editor.putString("inappservice_stock", new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP),"utf-8")); editor.commit(); } catch( Exception e ) { e.printStackTrace(); } }
protected void loadCipheredStock(){ mStock = new HashMap<String, Integer>(); try { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); String value = preferences.getString("inappservice_stock", ""); if (value.length() == 0) { return; } final byte[] bytes = Base64.decode(value,Base64.DEFAULT); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(getUniquePseudoID().toCharArray())); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf-8"), 20)); String json = new String(pbeCipher.doFinal(bytes),"utf-8"); JSONObject object = new JSONObject(json); Iterator<?> keys = object.keys(); while( keys.hasNext() ){ String pid = (String)keys.next(); this.mStock.put(pid, object.optInt(pid)); } } catch( Exception e) { e.printStackTrace(); } }