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

The following examples show how to use com.google.android.gms.safetynet.SafetyNet. 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: MainActivity.java    From android-security with Apache License 2.0 7 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    client = new GoogleApiClient.Builder(this)
            .addApi(SafetyNet.API)
            .enableAutoManage(this, this)
            .build();

    binding.root.setText(new RootBeer(this).isRooted() ? "Device is rooted" : "Device isn't rooted");
    binding.installation.setText(InstallationChecker.verifyInstaller(this) ? "Installed from Play Store" : "Installed from unknown source");

    binding.enviroment.setText((EnvironmentChecker.alternativeIsEmulator() ? "Running on an emulator" : "Running on a device")
            + (EnvironmentChecker.isDebuggable(this) ? " with debugger" : ""));

    binding.tampering.setText((InstallationChecker.checkPackage(this) ?
            "The package is consistent" : "The package was modified")
            + (SignatureUtils.checkSignature(this) ? " and the signature is ok" : " and the signature was changed!"));

    binding.setController(this);
}
 
Example #2
Source File: MainActivity.java    From android-security with Apache License 2.0 5 votes vote down vote up
@Override
public void requestSafetyNetCheck() {
    byte[] nonce = getRequestNonce();
    SafetyNet.SafetyNetApi.attest(client, nonce)
            .setResultCallback(result -> {
                if (result.getStatus().isSuccess()) {
                    showSafetyNetResult(result.getJwsResult());
                } else {
                    Log.e(TAG, "Error on SafetyNet request - Code ("
                            + result.getStatus().getStatusCode() + "): " +
                            "" + result.getStatus().getStatusMessage());
                }
            });
}
 
Example #3
Source File: SafetyNetUtils.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
public SafetyNetUtils(Context ctx, Callback callback) {
    this.ctx = ctx;
    this.callback = callback;

    GoogleApiClient.OnConnectionFailedListener googleApiConnectionFailedListener = connectionResult -> Log.e(TAG, "onConnectionFailed:" + connectionResult.toString());
    GoogleApiClient.ConnectionCallbacks googleApiConnectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            String logs = bundle == null ? "" : bundle.toString();
            callback.onResponse("GoogleApiClient onConnected " + logs);
        }

        @Override
        public void onConnectionSuspended(int i) {
            Log.d(TAG, "onConnectionSuspended" + i);
        }
    };


    Handler handler = new Handler(MyApplication.INSTANCE.safetyNetLooper.getLooper());
    googleApiClient = new GoogleApiClient.Builder(ctx)
            .addApi(SafetyNet.API)
            .addConnectionCallbacks(googleApiConnectionCallbacks)
            .addOnConnectionFailedListener(googleApiConnectionFailedListener)
            .setHandler(handler) //Run on a new thread
            .build();
    googleApiClient.connect();
    secureRandom = new SecureRandom();
}
 
Example #4
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 #5
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 #6
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();
                    }
                }
            });
}
 
Example #7
Source File: ApplicationModule.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@Singleton @Provides SafetyNetClient providesSafetyNetClient() {
  return SafetyNet.getClient(application);
}