/** * Create a new authentication provider. * * @param type The type for the provider. * @param ticketKey The ticket key for the provider. This can be any value and does not need to match user identifier. * This value will be used in the token provider callback for giving context. The only requirement * is that ticket key is different if registering a new provider (for example to switch user). * Typical implementations will pass user identifier as a value but it's not a requirement. * @param tokenProvider The token provider that will be used to get a current authentication token. */ public AuthenticationProvider(Type type, String ticketKey, TokenProvider tokenProvider) { mType = type; mTicketKey = ticketKey; mTicketKeyHash = ticketKey == null ? null : HashUtils.sha256(ticketKey); mTokenProvider = tokenProvider; }
@NonNull @VisibleForTesting static String sha256(@NonNull String data, String charsetName) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(data.getBytes(charsetName)); return encodeHex(digest.digest()); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { /* * Never happens as every device has UTF-8 support and SHA-256, * but if it ever happens make sure we propagate exception as unchecked. */ throw new RuntimeException(e); } }
@Test public void init() { new HashUtils(); }
/** * Hash data with sha256 and encodeHex output in hexadecimal. * * @param data data to hash. * @return hashed data in hexadecimal output. */ @NonNull public static String sha256(@NonNull String data) { return sha256(data, "UTF-8"); }
@NonNull static String computeReleaseHash(@NonNull PackageInfo packageInfo) { return HashUtils.sha256(packageInfo.packageName + ":" + packageInfo.versionName + ":" + DeviceInfoHelper.getVersionCode(packageInfo)); }
@Test(expected = RuntimeException.class) public void utf8NotFound() { try { HashUtils.sha256("", "Some Invalid Encoding"); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof UnsupportedEncodingException); throw e; } } }
@Test(expected = RuntimeException.class) @PrepareForTest(HashUtils.class) public void algorithmNotFound() throws NoSuchAlgorithmException { mockStatic(MessageDigest.class); NoSuchAlgorithmException cause = new NoSuchAlgorithmException(); doThrow(cause).when(MessageDigest.class); MessageDigest.getInstance(anyString()); try { HashUtils.sha256(""); } catch (RuntimeException e) { assertEquals(cause, e.getCause()); throw e; } }