com.google.android.gms.safetynet.SafetyNetApi Java Examples

The following examples show how to use com.google.android.gms.safetynet.SafetyNetApi. 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: SafetyNetSampleFragment.java    From android-play-safetynet with Apache License 2.0 6 votes vote down vote up
@Override
public void onSuccess(SafetyNetApi.AttestationResponse attestationResponse) {
    /*
     Successfully communicated with SafetyNet API.
     Use result.getJwsResult() to get the signed result data. See the server
     component of this sample for details on how to verify and parse this result.
     */
    mResult = attestationResponse.getJwsResult();
    Log.d(TAG, "Success! SafetyNet result:\n" + mResult + "\n");

        /*
         TODO(developer): Forward this result to your server together with
         the nonce for verification.
         You can also parse the JwsResult locally to confirm that the API
         returned a response by checking for an 'error' field first and before
         retrying the request with an exponential backoff.

         NOTE: Do NOT rely on a local, client-side only check for security, you
         must verify the response on a remote server!
        */
}
 
Example #2
Source File: FirstLaunchAnalytics.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
private void sendPlayProtectEvent() {
  safetyNetClient.listHarmfulApps()
      .addOnCompleteListener(task -> {
        boolean isActive = false;
        boolean isFlagged = false;
        String category = null;

        if (task.isSuccessful()) {
          isActive = true;
          isFlagged = false;
          SafetyNetApi.HarmfulAppsResponse result = task.getResult();
          category = getCategoryFlaggedByPlayProtect(result.getHarmfulAppsList());
          if (category != null) {
            isFlagged = true;
          }
        }
        Map<String, Object> data = new HashMap<>();
        data.put(IS_ACTIVE, isActive ? "true" : "false");
        data.put(FLAGGED, isFlagged ? "true" : "false");
        data.put(CATEGORY, category);
        analyticsManager.logEvent(data, PLAY_PROTECT_EVENT, AnalyticsManager.Action.OPEN,
            CONTEXT);
      });
}
 
Example #3
Source File: SafetyNetSampleFragment.java    From android-play-safetynet with Apache License 2.0 5 votes vote down vote up
private void sendSafetyNetRequest() {
    Log.i(TAG, "Sending SafetyNet API request.");

     /*
    Create a nonce for this request.
    The nonce is returned as part of the response from the
    SafetyNet API. Here we append the string to a number of random bytes to ensure it larger
    than the minimum 16 bytes required.
    Read out this value and verify it against the original request to ensure the
    response is correct and genuine.
    NOTE: A nonce must only be used once and a different nonce should be used for each request.
    As a more secure option, you can obtain a nonce from your own server using a secure
    connection. Here in this sample, we generate a String and append random bytes, which is not
    very secure. Follow the tips on the Security Tips page for more information:
    https://developer.android.com/training/articles/security-tips.html#Crypto
     */
    // TODO(developer): Change the nonce generation to include your own, used once value,
    // ideally from your remote server.
    String nonceData = "Safety Net Sample: " + System.currentTimeMillis();
    byte[] nonce = getRequestNonce(nonceData);

    /*
     Call the SafetyNet API asynchronously.
     The result is returned through the success or failure listeners.
     First, get a SafetyNetClient for the foreground Activity.
     Next, make the call to the attestation API. The API key is specified in the gradle build
     configuration and read from the gradle.properties file.
     */
    SafetyNetClient client = SafetyNet.getClient(getActivity());
    Task<SafetyNetApi.AttestationResponse> task = client.attest(nonce, BuildConfig.API_KEY);

    task.addOnSuccessListener(getActivity(), mSuccessListener)
            .addOnFailureListener(getActivity(), mFailureListener);

}
 
Example #4
Source File: SafetyNetCheck.java    From proofmode with GNU General Public License v3.0 5 votes vote down vote up
public void sendSafetyNetRequest(Context context, String nonceData, OnSuccessListener<SafetyNetApi.AttestationResponse> successListener, OnFailureListener failureListener) {
    if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
            == ConnectionResult.SUCCESS && sApiKey != null) {
        // The SafetyNet Attestation API is available.

        Log.d(TAG, "Sending SafetyNet API request.");

        byte[] nonce = getRequestNonce(nonceData);

        // Call the SafetyNet API asynchronously. The result is returned through the result callback.
        SafetyNet.getClient(context).attest(nonce, sApiKey).addOnSuccessListener(successListener).addOnFailureListener(failureListener);
    }
}
 
Example #5
Source File: SafetyNetUtils.java    From SecuritySample with Apache License 2.0 4 votes vote down vote up
public void requestAttestation(final boolean verifyJWSResponse) {
    if (!isGooglePlayServicesAvailable()) return;
    Log.v(TAG, "running SafetyNet.API Test");
    byte[] requestNonce = generateOneTimeRequestNonce();
    Log.d(TAG, "Nonce:" + Base64.encodeToString(requestNonce, Base64.DEFAULT));
    SafetyNet.SafetyNetApi.attest(googleApiClient, requestNonce)
            .setResultCallback(attestationResult -> {
                Status status = attestationResult.getStatus();
                boolean isSuccess = status.isSuccess();
                if (!isSuccess)
                    callback.onFail(ErrorMessage.SAFETY_NET_API_NOT_WORK, ErrorMessage.SAFETY_NET_API_NOT_WORK.name());
                else {
                    try {
                        final String jwsResult = attestationResult.getJwsResult();
                        final JwsHelper jwsHelper = new JwsHelper(jwsResult);
                        final AttestationResult response = new AttestationResult(jwsHelper.getDecodedPayload());
                        if (!verifyJWSResponse) {
                            callback.onResponse(response.getFormattedString());

                            //release SafetyNet HandlerThread
                            MyApplication.INSTANCE.safetyNetLooper.quit();
                        } else {
                            AndroidDeviceVerifier androidDeviceVerifier = new AndroidDeviceVerifier(ctx, jwsResult);
                            androidDeviceVerifier.verify(new AttestationTaskCallback() {
                                @Override
                                public void error(String errorMsg) {
                                    callback.onFail(ErrorMessage.FAILED_TO_CALL_GOOGLE_API_SERVICES, errorMsg);

                                    //release SafetyNet HandlerThread
                                    MyApplication.INSTANCE.safetyNetLooper.quit();
                                }

                                @Override
                                public void success(boolean isValidSignature) {
                                    if (isValidSignature)
                                        callback.onResponse("isValidSignature true\n\n" + response.getFormattedString());
                                    else
                                        callback.onFail(ErrorMessage.ERROR_VALID_SIGNATURE, ErrorMessage.ERROR_VALID_SIGNATURE.name());


                                    //release SafetyNet HandlerThread
                                    MyApplication.INSTANCE.safetyNetLooper.quit();
                                }
                            });
                        }
                    } catch (JSONException e) {
                        callback.onFail(ErrorMessage.EXCEPTION, e.getMessage());

                        //release SafetyNet HandlerThread
                        MyApplication.INSTANCE.safetyNetLooper.quit();
                    }
                }
            });
}