private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, NoSuchAlgorithmException { for (String alg : PBE_ALGORITHM_AR) { String baseAlgo = alg.split("/")[0].toUpperCase(); // only run the tests on longer key lengths if unlimited version // of JCE jurisdiction policy files are installed if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE && (baseAlgo.endsWith("TRIPLEDES") || alg .endsWith("AES_256"))) { out.println("keyStrength > 128 within " + alg + " will not run under global policy"); continue; } SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p); SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover" .toCharArray())); wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true); } }
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(); }
/** * Returns a specification (key material) of the given key * in the requested format. * * @param key the key * * @param keySpecCl the requested format in which the key material shall be * returned * * @return the underlying key specification (key material) in the * requested format * * @exception InvalidKeySpecException if the requested key * specification is inappropriate for the given key, or the * given key cannot be processed (e.g., the given key has an * unrecognized algorithm or format). */ protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl) throws InvalidKeySpecException { if (key instanceof javax.crypto.interfaces.PBEKey) { // Check if requested key spec is amongst the valid ones if ((keySpecCl != null) && PBEKeySpec.class.isAssignableFrom(keySpecCl)) { javax.crypto.interfaces.PBEKey pKey = (javax.crypto.interfaces.PBEKey) key; return new PBEKeySpec (pKey.getPassword(), pKey.getSalt(), pKey.getIterationCount(), pKey.getEncoded().length*8); } else { throw new InvalidKeySpecException("Invalid key spec"); } } else { throw new InvalidKeySpecException("Invalid key " + "format/algorithm"); } }
/** * @param param */ public JCEPBEKey( String algorithm, DERObjectIdentifier oid, int type, int digest, int keySize, int ivSize, PBEKeySpec pbeKeySpec, CipherParameters param) { this.algorithm = algorithm; this.oid = oid; this.type = type; this.digest = digest; this.keySize = keySize; this.ivSize = ivSize; this.pbeKeySpec = pbeKeySpec; this.param = param; }
/** * A method to get 64 random bytes deterministically based on user input * And to also fill the queue with numbers **/ private void fill_q(char[] sentence, char[] word, String encryption) throws NoSuchAlgorithmException, InvalidKeySpecException { // 512 bit key_length (64 bytes). Python and C++ use bytes rather than bits. KeySpec ks = new PBEKeySpec(sentence, chars_to_bytes(word), iterations, key_length_in_bytes * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(encryption); if (debug) { String hex_random_bytes = byte_array_to_hex(skf.generateSecret(ks).getEncoded()); System.out.println("PBKDF2: " + hex_random_bytes); } byte[] random_bytes = skf.generateSecret(ks).getEncoded(); for (byte b : random_bytes) { if (debug) { // & 0xFF ensures the int is unsigned System.out.println(((int) b) & 0xFF); } number_queue.add(((int) b) & 0xFF); } }
/** * 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( PBEKeySpec keySpec, int type, int hash, int keySize) { PBEParametersGenerator generator = makePBEGenerator(type, hash); byte[] key; CipherParameters param; key = convertPassword(type, keySpec); generator.init(key, keySpec.getSalt(), keySpec.getIterationCount()); param = generator.generateDerivedMacParameters(keySize); for (int i = 0; i != key.length; i++) { key[i] = 0; } return param; }
private static byte[] convertPassword(int type, PBEKeySpec keySpec) { byte[] key; if (type == PKCS12) { key = PBEParametersGenerator.PKCS12PasswordToBytes(keySpec.getPassword()); } else if (type == PKCS5S2_UTF8 || type == PKCS5S1_UTF8) { key = PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(keySpec.getPassword()); } else { key = PBEParametersGenerator.PKCS5PasswordToBytes(keySpec.getPassword()); } return key; }
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 UserAuth buildUserAuth(final UID uid, final String authKey) throws IllegalArgumentException { final UserAuth userAuth = new UserAuth(); final SecureRandom random = new SecureRandom(); final byte[] prefix = new byte[16]; // create salt random.nextBytes(prefix); userAuth.setUid(uid); userAuth.setPrefix(ByteString.copyFrom(prefix)); final PBEKeySpec spec = new PBEKeySpec(authKey.toCharArray(), prefix, 65536, 128); try { userAuth.setAuthKey(ByteString.copyFrom(secretKey.generateSecret(spec).getEncoded())); } catch (InvalidKeySpecException ikse) { throw new IllegalArgumentException(ikse.toString()); } return userAuth; }
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); }
/** * Creates a PBE key from a given PBE key specification. * * @param key the given PBE key specification */ PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException { char[] passwd = keySpec.getPassword(); if (passwd == null) { // Should allow an empty password. passwd = new char[0]; } // Accept "\0" to signify "zero-length password with no terminator". if (!(passwd.length == 1 && passwd[0] == 0)) { for (int i=0; i<passwd.length; i++) { if ((passwd[i] < '\u0020') || (passwd[i] > '\u007E')) { throw new InvalidKeySpecException("Password is not ASCII"); } } } this.key = new byte[passwd.length]; for (int i=0; i<passwd.length; i++) this.key[i] = (byte) (passwd[i] & 0x7f); java.util.Arrays.fill(passwd, ' '); type = keytype; }
/** * @param salt an array of random bytes to use for each (un)obfuscation * @param applicationId application identifier, e.g. the package name * @param deviceId device identifier. Use as many sources as possible to * create this unique identifier. */ public AESObfuscator(byte[] salt, String applicationId, String deviceId) { try { SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec = new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256); SecretKey tmp = factory.generateSecret(keySpec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM); mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV)); mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM); mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV)); } catch (GeneralSecurityException e) { // This can't happen on a compatible Android device. throw new RuntimeException("Invalid environment", e); } }
/** * Initiate the Cipher object for PBKDF2 algorithm using given "mode". * * @param mode Cipher mode: encrypt or decrypt * @return Cipher object for PBKDF2 algorithm * @throws GeneralSecurityException all security exceptions are thrown. */ @Override protected Cipher initCipher(int mode) throws GeneralSecurityException { Provider provider = Security.getProvider("SunJCE"); if (provider == null) { throw new RuntimeException("SunJCE provider does not exist."); } // Generate secret key PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo); SecretKey key = keyFactory.generateSecret(pbeKeySpec); // get Cipher instance Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider); cipher.init(mode, new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM), new IvParameterSpec(iv)); return cipher; }
public String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { // PBKDF2 with SHA-1 as the hashing algorithm. Note that the NIST // specifically names SHA-1 as an acceptable hashing algorithm for PBKDF2 String algorithm = "PBKDF2WithHmacSHA1"; // SHA-1 generates 160 bit hashes, so that's what makes sense here int derivedKeyLength = 160; // Pick an iteration count that works for you. The NIST recommends at // least 1,000 iterations: // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf // iOS 4.x reportedly uses 10,000: // http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-passwords/ int iterations = 20000; char[] pwd = new String(password).toCharArray(); KeySpec spec = new PBEKeySpec(pwd, Base64.getDecoder().decode(salt), iterations, derivedKeyLength); SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm); byte[] bytes = f.generateSecret(spec).getEncoded(); return Base64.getEncoder().encodeToString(bytes); }
/** * Reads the private key from an encrypted PKCS#8 file and returns it as an ECPrivateKey instance. * * @param A PKCS#8 (.key) file containing the private key with value "s" * @return The private key as an ECPrivateKey instance */ public static ECPrivateKey getPrivateKey(String keyFilePath) { Path fileLocation = Paths.get(keyFilePath); byte[] pkcs8ByteArray; try { pkcs8ByteArray = Files.readAllBytes(fileLocation); // The DER encoded private key is password-based encrypted and provided in PKCS#8. So we need to decrypt it first PBEKeySpec pbeKeySpec = new PBEKeySpec(GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray()); EncryptedPrivateKeyInfo encryptedPrivKeyInfo = new EncryptedPrivateKeyInfo(pkcs8ByteArray); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivKeyInfo.getAlgName()); Key secret = secretKeyFactory.generateSecret(pbeKeySpec); PKCS8EncodedKeySpec pkcs8PrivKeySpec = encryptedPrivKeyInfo.getKeySpec(secret); ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(pkcs8PrivKeySpec); return privateKey; } catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) { getLogger().error(e.getClass().getSimpleName() + " occurred while trying to access private key at " + "location '" + keyFilePath + "'"); return null; } }
/** * The key is generating by SecretKeyFactory and its value just copying in * the key field of MySecretKey class. So, this is real key derived using * the given algorithm. * * @param passPhrase some string intended to be a password * @param algo PBKDF2 algorithm * @param salt slat for PBKDF2 * @param iterationCount iteration count * @param keySize key size in bits * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt, int iterationCount, int keySize) throws InvalidKeySpecException, NoSuchAlgorithmException { this.algorithm = algo; this.salt = salt; this.itereationCount = iterationCount; this.keySize = keySize; this.pass = passPhrase; PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), this.salt, iterationCount, this.keySize); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo); SecretKey realKey = keyFactory.generateSecret(spec); this.keyLength = realKey.getEncoded().length; this.key = new byte[this.keyLength]; System.arraycopy(realKey.getEncoded(), 0, this.key, 0, this.keyLength); }
/** * Puts password in keystore under given alias. Secret password is secured with the entry password. * The keystore change is persistant. * @param alias alias to secret password * @param password password to store as secret * @param entryPassword password to secret password * @throws KeyStoreProviderException */ public void putPassword(String alias, String password, String entryPassword) throws KeyStoreProviderException { try { LOG.info(String.format("Putting password with alias %s in keystore ...", alias)); SecretKeyFactory skFactory = SecretKeyFactory.getInstance(SECRET_KEY_PASSWORD_ALGORITHM); SecretKey secret = skFactory.generateSecret(new PBEKeySpec(password.toCharArray())); this.keystore.setEntry(alias, new KeyStore.SecretKeyEntry(secret), new KeyStore.PasswordProtection(entryPassword.toCharArray())); factory.persist(this.keystore); } catch (NoSuchAlgorithmException nsae) { throw new KeyStoreProviderException("Algorithm used to create PBE secret cannot be found.", nsae); } catch (InvalidKeySpecException ikse) { throw new KeyStoreProviderException("Invalid key spec used to create PBE secret.", ikse); } catch (KeyStoreException kse) { throw new KeyStoreProviderException("Failed to put PBE secret to keystore.", kse); } catch (Exception e) { throw new KeyStoreProviderException("Failed to put PBE secret in keystore", e); } }
/** * The key is generating by SecretKeyFactory and its value just copying * in the key field of MySecretKey class. So, this is real key derived * using the given algo. */ public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1, int iterationCount, int keySize) throws InvalidKeySpecException, NoSuchAlgorithmException { algorithm = algo; salt = salt1; itereationCount = iterationCount; pass = passPhrase; PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keySize); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo); SecretKey realKey = keyFactory.generateSecret(spec); keyLength = realKey.getEncoded().length; key = new byte[keyLength]; System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength); }
/** * Returns a specification (key material) of the given key * in the requested format. * * @param key the key * * @param keySpec the requested format in which the key material shall be * returned * * @return the underlying key specification (key material) in the * requested format * * @exception InvalidKeySpecException if the requested key * specification is inappropriate for the given key, or the * given key cannot be processed (e.g., the given key has an * unrecognized algorithm or format). */ protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl) throws InvalidKeySpecException { if (key instanceof javax.crypto.interfaces.PBEKey) { // Check if requested key spec is amongst the valid ones if ((keySpecCl != null) && PBEKeySpec.class.isAssignableFrom(keySpecCl)) { javax.crypto.interfaces.PBEKey pKey = (javax.crypto.interfaces.PBEKey) key; return new PBEKeySpec (pKey.getPassword(), pKey.getSalt(), pKey.getIterationCount(), pKey.getEncoded().length*8); } else { throw new InvalidKeySpecException("Invalid key spec"); } } else { throw new InvalidKeySpecException("Invalid key " + "format/algorithm"); } }
/** * Constructor for initializing AesSerializer. * * @param key The key or password to use for encrypting objects before saving them. * @param salt The salt to salt the password with. * @see <a href="https://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/PBEKeySpec.html">PBEKeySpec</a> * @see <a href="https://javarevisited.blogspot.com/2012/03/why-character-array-is-better-than.html"> * Why character array is better than String for Storing password in Java</a> */ public AesSerializer(char[] key, byte[] salt) { if (key == null) throw new NullPointerException("key == null"); try { SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec = new PBEKeySpec(key, salt, DERIVATION_ITERATION_COUNT, KEY_SIZE); SecretKey tmp = factory.generateSecret(keySpec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), ENCRYPTION_ALGORITHM); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV); encryptCipher = Cipher.getInstance(CIPHER_ALGORITHM); encryptCipher.init(Cipher.ENCRYPT_MODE, secret, ivParameterSpec); decryptCipher = Cipher.getInstance(CIPHER_ALGORITHM); decryptCipher.init(Cipher.DECRYPT_MODE, secret, ivParameterSpec); } catch (Exception e) { ExceptionUtil.sneakyThrow(e); throw new IllegalStateException(); } }
/** * This method will hash the password and salt combination. Be careful, this method will erase the password after hashed it. * You must be sure that you do not need it after using this method. * * @param password the password who needs to be hashed * @param salt some list of <code>byte</code> which will be included in the password * @return a hash of the password and salting combination. */ public static byte[] hash(char[] password, byte[] salt) { final PBEKeySpec spec = new PBEKeySpec(password, salt, SecurityUtils.ITERATIONS, SecurityUtils.KEY_LENGTH); try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SecurityUtils.ALGORITHM); SecretKey key = secretKeyFactory.generateSecret(spec); return key.getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { LOGGER.debug(e.getMessage(), e); throw new SecurityException(e); } finally { // erase the password in the char array in order to not retrieve it in the java memory spec.clearPassword(); } }
public static PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception { String privateKeyPEM = key .replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "") .replace("-----END ENCRYPTED PRIVATE KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM); EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(epkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters()); return epkInfo.getKeySpec(cipher); }
public PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception { String privateKeyPEM = key .replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "") .replace("-----END ENCRYPTED PRIVATE KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM); EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(epkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters()); return epkInfo.getKeySpec(cipher); }
public void bad7() throws Exception { byte[] bytes = new byte[2]; char[] pwd = "secret7".toCharArray(); new PBEKeySpec(pwd); new PBEKeySpec(pwd, bytes, 1); new PBEKeySpec(pwd, bytes, 1, 1); PasswordAuthentication auth = new PasswordAuthentication("user", pwd); PasswordCallback callback = new PasswordCallback("str", true); callback.setPassword(pwd); KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(pwd); KerberosKey key = new KerberosKey(null, pwd, "alg"); KeyManagerFactory.getInstance("").init(null, pwd); }
CipherGenerator(String algo) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException { // Do initialization byte[] salt = TestUtilities.generateBytes(IV_LENGTH); int iterCnt = 6; SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.split("/")[0]); SecretKey key = skf .generateSecret(new PBEKeySpec(PASSWD.toCharArray())); AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iterCnt); initCiphers(algo, key, aps); }
AesUtility(String passPhrase, byte [] salt, int iterationCount, int keyStrength) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength); SecretKey secret = factory.generateSecret(spec); key = new SecretKeySpec(secret.getEncoded(), "AES"); dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); }
private static void testPBKSecret(String algorithm) throws Exception { byte[] salt = new byte[8]; new Random().nextBytes(salt); char[] password = new char[] {'f', 'o', 'o'}; PBEKeySpec pbeKeySpec = new PBEKeySpec(PASS_PHRASE.toCharArray(), salt, ITERATION_COUNT, KEY_SIZE); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(algorithm, SunJCEProvider); testCleanupSecret(algorithm, keyFac.generateSecret(pbeKeySpec)); }
/** * 生成密文 * * @param password 明文密码 * @param salt 盐值 * @return 密文 */ public static String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { KeySpec spec = new PBEKeySpec(password.toCharArray(), fromHex(salt), PBKDF2_ITERATIONS, HASH_BIT_SIZE); SecretKeyFactory f = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return toHex(f.generateSecret(spec).getEncoded()); }
protected String encrypt(String value ) { try { final byte[] bytes = value!=null ? value.getBytes(UTF8) : new byte[0]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Secure.getString(context.getContentResolver(), 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); } }
protected String decrypt(String value){ try { final byte[] bytes = value!=null ? Base64.decode(value, Base64.DEFAULT) : new byte[0]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID).getBytes(UTF8), 20)); return new String(pbeCipher.doFinal(bytes),UTF8); } catch( Exception e) { Log.e(this.getClass().getName(), "Warning, could not decrypt the value. It may be stored in plaintext. "+e.getMessage()); return value; } }
public void setDecParameters(byte[] Encrypted, int alg, String pwd, int KeySize, String mode) throws InvalidKeySpecException, NoSuchAlgorithmException { switch (alg) { case 7: case 8: case 1: this.ivData = new byte[KeySize/8]; System.arraycopy(Encrypted, 0, this.ivData, 0, blockSize/8); break; default: this.ivData = new byte[128/8]; System.arraycopy(Encrypted, 0, this.ivData, 0, 128/8); break; } byte[] salt = new byte[16]; System.arraycopy(Encrypted, Encrypted.length - 16 , salt, 0, 16); switch (mode) { case "Q": factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); break; default: factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); break; } spec = new PBEKeySpec (pwd.toCharArray(), salt, 65536, KeySize); tmp = factory.generateSecret(spec); keyParam = new KeyParameter(tmp.getEncoded()); }
/** * construct a key and iv (if necessary) suitable for use with a * Cipher. */ static CipherParameters makePBEParameters( PBEKeySpec keySpec, int type, int hash, int keySize, int ivSize) { PBEParametersGenerator generator = makePBEGenerator(type, hash); byte[] key; CipherParameters param; if (type == PKCS12) { key = PBEParametersGenerator.PKCS12PasswordToBytes(keySpec.getPassword()); } else { key = PBEParametersGenerator.PKCS5PasswordToBytes(keySpec.getPassword()); } generator.init(key, keySpec.getSalt(), keySpec.getIterationCount()); if (ivSize != 0) { param = generator.generateDerivedParameters(keySize, ivSize); } else { param = generator.generateDerivedParameters(keySize); } for (int i = 0; i != key.length; i++) { key[i] = 0; } return param; }
public PBECipherWrapper( Provider p, String algo, String passwd, PrintStream out) throws Exception { super(algo, SecretKeyFactory.getInstance( new StringTokenizer(algo, "/").nextToken(), p).generateSecret( new PBEKeySpec(passwd.toCharArray())), Cipher.getInstance(algo, p), out); int SALT_SIZE = 8; aps = new PBEParameterSpec(generateSalt(SALT_SIZE), ITERATION_COUNT); }
/** * Get SecretKey for the given PBKDF2 algorithm. * * @param thePBKDF2Algorithm - PBKDF2 algorithm * @return SecretKey according to thePBKDF2Algorithm * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ protected SecretKey getSecretKey(String thePBKDF2Algorithm) throws NoSuchAlgorithmException, InvalidKeySpecException { // Prepare salt byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation new SecureRandom().nextBytes(salt); // Generate secret key PBEKeySpec pbeKeySpec = new PBEKeySpec( "A #pwd# implied to be hidden!".toCharArray(), salt, 1000, 128); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(thePBKDF2Algorithm); return keyFactory.generateSecret(pbeKeySpec); }