at.favre.lib.bytes.Bytes Java Examples
The following examples show how to use
at.favre.lib.bytes.Bytes.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BcryptTool.java From bcrypt with Apache License 2.0 | 6 votes |
/** * Execute the given arguments and executes the appropriate actions * * @param arguments * @param stream * @param errorStream * @return the exit code of the tool */ static int execute(Arg arguments, PrintStream stream, PrintStream errorStream) { if (arguments == null) { return 2; } if (arguments.checkBcryptHash != null) { // verify mode BCrypt.Result result = BCrypt.verifyer().verify(arguments.password, arguments.checkBcryptHash); if (!result.validFormat) { System.err.println("Invalid bcrypt format."); return 3; } if (result.verified) { stream.println("Hash verified."); } else { errorStream.println("Provided hash does not verify against given password."); return 1; } } else { // hash mode byte[] salt = arguments.salt == null ? Bytes.random(16).array() : arguments.salt; byte[] hash = BCrypt.withDefaults().hash(arguments.costFactor, salt, charArrayToByteArray(arguments.password, StandardCharsets.UTF_8)); stream.println(new String(hash, StandardCharsets.UTF_8)); } return 0; }
Example #2
Source File: SecureSharedPreferences.java From armadillo with Apache License 2.0 | 6 votes |
private byte[] getPreferencesSalt(StringMessageDigest stringMessageDigest, DataObfuscator dataObfuscator, SecureRandom secureRandom) { prefSaltContentKey = stringMessageDigest.derive(PREFERENCES_SALT_KEY, "prefName"); String prefSaltBase64 = sharedPreferences.getString(prefSaltContentKey, null); byte[] prefSalt; if (prefSaltBase64 == null) { Timber.v("create new preferences random salt"); byte[] generatedPrefSalt = Bytes.random(PREFERENCES_SALT_LENGTH_BYTES, secureRandom).array(); try { prefSalt = Bytes.wrap(generatedPrefSalt).copy().array(); dataObfuscator.obfuscate(generatedPrefSalt); sharedPreferences.edit().putString(prefSaltContentKey, Bytes.wrap(generatedPrefSalt).encodeBase64()).apply(); } finally { Bytes.wrapNullSafe(generatedPrefSalt).mutable().secureWipe(); } } else { byte[] obfuscatedPrefSalt = Bytes.parseBase64(prefSaltBase64).array(); dataObfuscator.deobfuscate(obfuscatedPrefSalt); prefSalt = obfuscatedPrefSalt; } return prefSalt; }
Example #3
Source File: ArmadilloRegressionTest.java From armadillo with Apache License 2.0 | 6 votes |
@Test @Ignore public void generateTestData() { MockSharedPref mockSharedPref = new MockSharedPref(); ArmadilloSharedPreferences a = Armadillo.create(mockSharedPref) .encryptionFingerprint(Bytes.parseHex("385b2db3ca08845c52bc86b3d06ee903").array()) .compress() .cryptoProtocolVersion(748179) .contentKeyDigest(Bytes.parseHex("f31058e8b67ed2198a8366733b7b039b").array()) .supportVerifyPassword(true) .keyStretchingFunction(new FastKeyStretcher()) .password("乨ØDzDzɻaД\u058DAאaABB12\u08A1A2$_".toCharArray()).build(); a.edit() .putInt("aInt", 5623) .putBoolean("aBoolean", true) .putFloat("aFloat", 8281.923452f) .putLong("aLong", 108731871230172893L) .putString("string", "87adhpn2p807 1807g oasfbdfblskdfb") .commit(); for (Map.Entry<String, ?> stringEntry : mockSharedPref.getAll().entrySet()) { System.out.println(".putString(\"" + stringEntry.getKey() + "\", \"" + stringEntry.getValue() + "\")"); } }
Example #4
Source File: HKDFTest.java From hkdf with Apache License 2.0 | 6 votes |
@Test public void testSmallArrayInput() { byte[] b1 = HKDF.fromHmacSha256().extractAndExpand(new byte[16], new byte[]{1}, "smth".getBytes(), 64); byte[] b2 = HKDF.fromHmacSha256().extractAndExpand(new byte[16], new byte[]{1}, "smth".getBytes(), 64); byte[] b3 = HKDF.fromHmacSha256().extractAndExpand(new byte[16], new byte[1], "smth".getBytes(), 64); byte[] b4 = HKDF.fromHmacSha256().extractAndExpand(new byte[16], new byte[2], "smth".getBytes(), 64); assertArrayEquals(b1, b2); assertFalse(Arrays.equals(b1, b3)); assertFalse(Arrays.equals(b1, b4)); assertFalse(Arrays.equals(b3, b4)); System.out.println(Bytes.wrap(b1).encodeHex()); System.out.println(Bytes.wrap(b2).encodeHex()); System.out.println(Bytes.wrap(b3).encodeHex()); System.out.println(Bytes.wrap(b4).encodeHex()); }
Example #5
Source File: LongPasswordStrategyTest.java From bcrypt with Apache License 2.0 | 6 votes |
@Test public void testSha512HashStrategy() { LongPasswordStrategy strategy = new LongPasswordStrategy.Sha512DerivationStrategy(maxLength); byte[] byteArray; for (int i = 1; i < maxLength; i++) { byteArray = Bytes.random(i).array(); assertSame(byteArray, strategy.derive(byteArray)); } for (int i = maxLength; i < maxLength * 2; i++) { byteArray = Bytes.random(maxLength).array(); assertArrayEquals(Bytes.wrap(byteArray).hash("SHA-512").array(), strategy.derive(byteArray)); assertTrue(byteArray.length <= maxLength); System.out.println(Bytes.wrap(byteArray).encodeHex()); } }
Example #6
Source File: LongPasswordStrategyTest.java From bcrypt with Apache License 2.0 | 6 votes |
@Test public void testTruncateStrategy() { LongPasswordStrategy strategy = new LongPasswordStrategy.TruncateStrategy(maxLength); byte[] byteArray; for (int i = 1; i < maxLength; i++) { byteArray = Bytes.random(i).array(); assertSame(byteArray, strategy.derive(byteArray)); } testTooLongTruncate(maxLength, maxLength, strategy); for (int i = 1; i < maxLength; i++) { testTooLongTruncate(maxLength + i, maxLength, strategy); } }
Example #7
Source File: LongPasswordStrategyTest.java From bcrypt with Apache License 2.0 | 6 votes |
@Test public void testStrictLengthStrategy() { LongPasswordStrategy strategy = new LongPasswordStrategy.StrictMaxPasswordLengthStrategy(maxLength); byte[] byteArray; for (int i = 1; i < maxLength; i++) { byteArray = Bytes.random(i).array(); assertSame(byteArray, strategy.derive(byteArray)); } checkExpectToFail(maxLength, strategy); for (int i = 1; i < maxLength; i++) { checkExpectToFail(maxLength + i, strategy); } }
Example #8
Source File: DefaultEncryptionProtocolTest.java From armadillo with Apache License 2.0 | 6 votes |
@Test public void testWipeCache() throws Exception { EncryptionProtocol protocol = createDefaultProtocol(new TestEncryptionFingerprint()); String contentKey = Bytes.random(20).encodeHex(); byte[] content = Bytes.random(354).array(); char[] pw = "乨ØDzDzɻaД\u058DAא\u08A1A2$ᶀṻὉ\u202A₸ꜽ!ö\uD83E\uDD2Fײַ".toCharArray(); byte[] encrypted = protocol.encrypt(contentKey, pw, content); protocol.decrypt(contentKey, pw, encrypted); protocol.decrypt(contentKey, pw, encrypted); protocol.decrypt(contentKey, pw, encrypted); protocol.wipeDerivedPasswordCache(); protocol.decrypt(contentKey, pw, encrypted); }
Example #9
Source File: SecureSharedPreferencesTest.java From armadillo with Apache License 2.0 | 6 votes |
@Test public void advancedTest() { String userId = "1234"; SharedPreferences preferences = Armadillo.create(context, "myCustomPreferences") .password("mySuperSecretPassword".toCharArray()) //use user based password .keyStretchingFunction(new PBKDF2KeyStretcher()) //use PBKDF2 as user password kdf .contentKeyDigest(Bytes.from(getAndroidId(context)).array()) //use custom content key digest salt .secureRandom(new SecureRandom()) //provide your own secure random for salt/iv generation .encryptionFingerprint(context, userId.getBytes(StandardCharsets.UTF_8)) //add the user id to fingerprint .supportVerifyPassword(true) //enables optional password validation support `.isValidPassword()` .enableKitKatSupport(true) //enable optional kitkat support .build(); preferences.edit().putString("key1", "string").apply(); String s = preferences.getString("key1", null); assertEquals("string", s); }
Example #10
Source File: AesCbcEncryption.java From armadillo with Apache License 2.0 | 5 votes |
private void verifyMac(byte[] rawEncryptionKey, byte[] cipherText, byte[] iv, byte[] mac, @Nullable byte[] associatedData) throws AuthenticatedEncryptionException { byte[] actualMac = macCipherText(rawEncryptionKey, cipherText, iv, associatedData); if (!Bytes.wrap(mac).equalsConstantTime(actualMac)) { throw new AuthenticatedEncryptionException("encryption integrity exception: mac does not match"); } }
Example #11
Source File: BcryptTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void testHashDataWipe() { Bytes salt = Bytes.random(16); Bytes hash = Bytes.random(23); BCrypt.HashData hashData = new BCrypt.HashData(6, BCrypt.Version.VERSION_2A, salt.copy().array(), hash.copy().array()); assertTrue(hash.equals(hashData.rawHash)); assertTrue(salt.equals(hashData.rawSalt)); hashData.wipe(); assertFalse(hash.equals(hashData.rawHash)); assertFalse(salt.equals(hashData.rawSalt)); }
Example #12
Source File: BcryptTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void verifyIncorrectStrictVersion() { BCrypt.Hasher bCrypt = BCrypt.with(BCrypt.Version.VERSION_2Y); byte[] pw = "78PHasdhklöALÖö".getBytes(); byte[] hash = bCrypt.hash(5, Bytes.random(16).array(), pw); BCrypt.Result result = BCrypt.verifyer(BCrypt.Version.VERSION_2A).verifyStrict(pw, hash); assertResult(result, false, BCrypt.Version.VERSION_2Y, 5); }
Example #13
Source File: HKDFTest.java From hkdf with Apache License 2.0 | 5 votes |
@Test public void simpleUseCase() throws Exception { //if no dynamic salt is available, a static salt is better than null byte[] staticSalt32Byte = new byte[]{(byte) 0xDA, (byte) 0xAC, 0x3E, 0x10, 0x55, (byte) 0xB5, (byte) 0xF1, 0x3E, 0x53, (byte) 0xE4, 0x70, (byte) 0xA8, 0x77, 0x79, (byte) 0x8E, 0x0A, (byte) 0x89, (byte) 0xAE, (byte) 0x96, 0x5F, 0x19, 0x5D, 0x53, 0x62, 0x58, (byte) 0x84, 0x2C, 0x09, (byte) 0xAD, 0x6E, 0x20, (byte) 0xD4}; //example input byte[] sharedSecret = Bytes.random(256).array(); HKDF hkdf = HKDF.fromHmacSha256(); //extract the "raw" data to create output with concentrated entropy byte[] pseudoRandomKey = hkdf.extract(staticSalt32Byte, sharedSecret); //create expanded bytes for e.g. AES secret key and IV byte[] expandedAesKey = hkdf.expand(pseudoRandomKey, "aes-key".getBytes(StandardCharsets.UTF_8), 16); byte[] expandedIv = hkdf.expand(pseudoRandomKey, "aes-iv".getBytes(StandardCharsets.UTF_8), 16); //Example boilerplate encrypting a simple string with created key/iv SecretKey key = new SecretKeySpec(expandedAesKey, "AES"); //AES-128 key byte[] message = "my secret message".getBytes(StandardCharsets.UTF_8); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(expandedIv)); byte[] encrypted = cipher.doFinal(message); assertNotNull(encrypted); assertTrue(encrypted.length > 0); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(expandedIv)); byte[] decrypted = cipher.doFinal(encrypted); assertArrayEquals(message, decrypted); assertFalse(Arrays.equals(encrypted, decrypted)); }
Example #14
Source File: ArmadilloBcryptKeyStretcher.java From armadillo with Apache License 2.0 | 5 votes |
/** * Computes the Bcrypt hash of a password. * * @param password the password to hash. * @param salt the salt * @param logRounds log2(Iterations). e.g. 12 ==> 2^12 = 4,096 iterations * @return the Bcrypt hash of the password */ private static byte[] bcrypt(byte[] salt, char[] password, int logRounds) { StrictMode.noteSlowCall("bcrypt is a very expensive call and should not be done on the main thread"); Bytes passwordBytes = Bytes.empty(); try { passwordBytes = Bytes.from(password); return BCrypt.with(BCrypt.Version.VERSION_2A).hashRaw(logRounds, HKDF.fromHmacSha256().expand(salt, "bcrypt-salt".getBytes(), 16), HKDF.fromHmacSha256().expand(passwordBytes.array(), "bcrypt-pw".getBytes(), 71)).rawHash; } finally { passwordBytes.mutable().secureWipe(); } }
Example #15
Source File: SecureSharedPreferences.java From armadillo with Apache License 2.0 | 5 votes |
@Override public boolean isValidPassword() { StrictMode.noteSlowCall("checking password should only be done in a background thread"); if (!supportVerifyPassword) { throw new UnsupportedOperationException("support verify password is not enabled"); } try { String storedValue = getString(PASSWORD_VALIDATION_KEY, null); return storedValue != null && Bytes.parseBase64(storedValue).equalsConstantTime(preferencesSalt); } catch (SecureSharedPreferenceCryptoException e) { return false; } }
Example #16
Source File: EncryptionFingerprintFactory.java From armadillo with Apache License 2.0 | 5 votes |
/** * Gets the SHA-256 hashed fingerprint of the APK signature * * @param context from Android * @return 32 bytes sha256 hash */ private static byte[] getApkSignatureHash(Context context) { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { @SuppressLint("PackageManagerGetSignatures") PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : packageInfo.signatures) { bos.write(signature.toByteArray()); } return Bytes.wrap(bos.toByteArray()).hashSha256().array(); } catch (Exception e) { throw new IllegalStateException("could not get apk signature hash", e); } }
Example #17
Source File: SecureSharedPreferences.java From armadillo with Apache License 2.0 | 5 votes |
@Override public SharedPreferences.Editor putStringSet(String key, @Nullable Set<String> values) { final String keyHash = encryptionProtocol.deriveContentKey(key); if (values == null) { internalEditor.remove(encryptionProtocol.deriveContentKey(key)); } else { final Set<String> encryptedValues = new HashSet<>(values.size()); for (String value : values) { encryptedValues.add(encryptToBase64(keyHash, password, Bytes.from(value).array())); } internalEditor.putStringSet(keyHash, encryptedValues); } return this; }
Example #18
Source File: ASecureSharedPreferencesTest.java From armadillo with Apache License 2.0 | 5 votes |
@Test public void testWithDifferentContentDigest() { preferenceSmokeTest(create("contentDigest1", null) .contentKeyDigest(8).build()); preferenceSmokeTest(create("contentDigest2", null) .contentKeyDigest(Bytes.random(16).array()).build()); preferenceSmokeTest(create("contentDigest3", null) .contentKeyDigest((providedMessage, usageName) -> Bytes.from(providedMessage).append(usageName).encodeUtf8()).build()); }
Example #19
Source File: AesCbcEncryption.java From armadillo with Apache License 2.0 | 5 votes |
@Override public byte[] encrypt(byte[] rawEncryptionKey, byte[] rawData, @Nullable byte[] associatedData) throws AuthenticatedEncryptionException { checkAesKey(rawEncryptionKey); byte[] iv = null; byte[] encrypted = null; byte[] mac = null; try { iv = new byte[IV_LENGTH_BYTE]; secureRandom.nextBytes(iv); final Cipher cipherEnc = getCipher(); cipherEnc.init(Cipher.ENCRYPT_MODE, createEncryptionKey(rawEncryptionKey), new IvParameterSpec(iv)); encrypted = cipherEnc.doFinal(rawData); mac = macCipherText(rawEncryptionKey, encrypted, iv, associatedData); ByteBuffer byteBuffer = ByteBuffer.allocate(1 + iv.length + 1 + mac.length + encrypted.length); byteBuffer.put((byte) iv.length); byteBuffer.put(iv); byteBuffer.put((byte) mac.length); byteBuffer.put(mac); byteBuffer.put(encrypted); return byteBuffer.array(); } catch (Exception e) { throw new AuthenticatedEncryptionException("could not encrypt", e); } finally { Bytes.wrapNullSafe(iv).mutable().secureWipe(); Bytes.wrapNullSafe(encrypted).mutable().secureWipe(); Bytes.wrapNullSafe(mac).mutable().secureWipe(); } }
Example #20
Source File: SecureSharedPreferences.java From armadillo with Apache License 2.0 | 5 votes |
@Override public long getLong(String key, long defaultValue) { final String keyHash = encryptionProtocol.deriveContentKey(key); final String encryptedValue = sharedPreferences.getString(keyHash, null); if (encryptedValue == null) { return defaultValue; } byte[] bytes = decrypt(keyHash, password, encryptedValue); if (bytes == null) { return defaultValue; } return Bytes.from(bytes).toLong(); }
Example #21
Source File: BCryptParserTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void parseDifferentCostFactors() throws Exception { for (int cost = 4; cost < 10; cost++) { byte[] salt = Bytes.random(16).array(); byte[] hash = BCrypt.withDefaults().hash(cost, salt, "12345".getBytes()); BCrypt.HashData parts = parser.parse(hash); assertEquals(cost, parts.cost); assertEquals(BCrypt.Version.VERSION_2A, parts.version); assertArrayEquals(salt, parts.rawSalt); assertEquals(23, parts.rawHash.length); System.out.println(parts); } }
Example #22
Source File: BcryptTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void testLongHashedPassword() { byte[] pw = Bytes.random(DEFAULT_VERSION.allowedMaxPwLength + 2).array(); byte[] salt = Bytes.random(16).array(); byte[] bcryptHashBytes1 = BCrypt.with(LongPasswordStrategies.hashSha512(DEFAULT_VERSION)).hash(4, salt, pw); byte[] bcryptHashBytes2 = BCrypt.with(LongPasswordStrategies.hashSha512(DEFAULT_VERSION)).hash(4, salt, Bytes.wrap(pw).resize(DEFAULT_VERSION.allowedMaxPwLength + 1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); assertFalse(Bytes.wrap(bcryptHashBytes1).equals(bcryptHashBytes2)); }
Example #23
Source File: BcryptTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void testVariousPwLengthShouldBeDifferentHashes() { Bytes pw = Bytes.random(256); byte[] salt = Bytes.random(16).array(); Set<String> hashes = new HashSet<>(); for (int i = 0; i < 72; i++) { BCrypt.HashData data = BCrypt.with(LongPasswordStrategies.truncate(DEFAULT_VERSION)).hashRaw(4, salt, pw.resize(i, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); String hashHexString = Bytes.wrap(data.rawHash).encodeHex(); assertFalse("hash already in set for length " + i, hashes.contains(hashHexString)); hashes.add(hashHexString); } }
Example #24
Source File: BcryptTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test @Repeat(20) public void hashRandomByteArrays() { byte[] pw = Bytes.random(new Random().nextInt(68) + 2).array(); byte[] hash = BCrypt.withDefaults().hash(4, pw); assertTrue(BCrypt.verifyer().verify(pw, hash).verified); System.out.println(Bytes.wrap(hash).encodeUtf8()); }
Example #25
Source File: BcryptTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void testSimpleBcryptHashes() { byte[] salt = new byte[]{0x5E, (byte) 0xFA, (byte) 0xA7, (byte) 0xA3, (byte) 0xD9, (byte) 0xDF, 0x6E, (byte) 0x7F, (byte) 0x8C, 0x78, (byte) 0x96, (byte) 0xB1, 0x7B, (byte) 0xA7, 0x6E, 0x01}; BCrypt.Hasher bCrypt = BCrypt.withDefaults(); for (int i = 4; i < 10; i++) { byte[] hash = bCrypt.hash(i, salt, "abcdefghijkl1234567öäü-,:".getBytes()); assertEquals(60, hash.length); System.out.println(Bytes.wrap(hash).encodeUtf8()); } }
Example #26
Source File: ASecureSharedPreferencesTest.java From armadillo with Apache License 2.0 | 5 votes |
@Test public void simpleMultipleStringGet() { SharedPreferences preferences = create("manytest", null).build(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 100; j++) { String content = "testäI/_²~" + Bytes.random(64 + j).encodeHex(); preferences.edit().putString("k" + j, content).commit(); assertEquals(content, preferences.getString("k" + j, null)); } } }
Example #27
Source File: LongPasswordStrategyTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void testPassThroughStrategy() { LongPasswordStrategy strategy = new LongPasswordStrategy.PassThroughStrategy(); byte[] byteArray; for (int i = 1; i < 64; i++) { byteArray = Bytes.random(i).array(); assertSame(byteArray, strategy.derive(byteArray)); } }
Example #28
Source File: BCryptParserTest.java From bcrypt with Apache License 2.0 | 5 votes |
@Test public void parseDifferentVersions() throws Exception { for (BCrypt.Version version : BCrypt.Version.SUPPORTED_VERSIONS) { byte[] salt = Bytes.random(16).array(); byte[] hash = BCrypt.with(version).hash(6, salt, "hs61i1oAJhdasdÄÄ".getBytes(StandardCharsets.UTF_8)); BCrypt.HashData parts = parser.parse(hash); assertEquals(version, parts.version); assertEquals(6, parts.cost); assertArrayEquals(salt, parts.rawSalt); assertEquals(23, parts.rawHash.length); System.out.println(parts); } }
Example #29
Source File: ByteArrayObfuscatorTest.java From armadillo with Apache License 2.0 | 5 votes |
@Test public void obfuscateVariousLengths() { testIntern(Bytes.random(1).array()); testIntern(Bytes.random(2).array()); testIntern(Bytes.random(3).array()); testIntern(Bytes.random(3).array()); testIntern(Bytes.random(16).array()); testIntern(Bytes.random(23).array()); testIntern(Bytes.random(24).array()); testIntern(Bytes.random(25).array()); testIntern(Bytes.random(32).array()); testIntern(Bytes.random(512).array()); }
Example #30
Source File: LongPasswordStrategyTest.java From bcrypt with Apache License 2.0 | 5 votes |
private void checkExpectToFail(int maxLength, LongPasswordStrategy strategy) { byte[] byteArray; try { byteArray = Bytes.random(maxLength).array(); assertArrayEquals(byteArray, strategy.derive(byteArray)); fail(); } catch (IllegalArgumentException ignored) { } catch (Exception e) { fail(); } }