谷歌如何验证Android SHA1指纹和包装?

时间:2015-07-23 13:47:40

标签: android google-api google-translate

我正在努力使我的Google翻译API工作,但目前我无法找到方法。这就是我在Google Developer Console中设置内容的方式:
 我已经使用调试证书设置了SHA1指纹。包名称 - " bg.webmap.wordy"(实际名称)。当我尝试打电话时," ipRefererBlocked"在JSON中返回错误。但是当我删除指纹和包名称时,它工作得很好,但是每个人都可以使用这个键,所以它非常不安全。所以我的问题是身份验证。
在调用API时,我的应用会自动发送此指纹吗?我应该自己发送以及如何发送?可能问题出在调试证书中?

1 个答案:

答案 0 :(得分:6)

  

我的应用会在API发布时自动发送此指纹吗?   叫?

NO!

  

我应该自己发送以及如何发送?

YES!

为Android应用设置API密钥限制时,您指定了包名称和SHA-1证书指纹。因此,当您向Google发送请求时,您必须在每个请求的标头中添加这些信息。

怎么样?

As answered here,您需要从代码中获取软件包名称和SHA证书,然后添加到请求标头。

获取SHA证书:

/**
 * Gets the SHA1 signature, hex encoded for inclusion with Google Cloud Platform API requests
 *
 * @param packageName Identifies the APK whose signature should be extracted.
 * @return a lowercase, hex-encoded
 */
public static String getSignature(@NonNull PackageManager pm, @NonNull String packageName) {
    try {
        PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        if (packageInfo == null
                || packageInfo.signatures == null
                || packageInfo.signatures.length == 0
                || packageInfo.signatures[0] == null) {
            return null;
        }
        return signatureDigest(packageInfo.signatures[0]);
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }
}

private static String signatureDigest(Signature sig) {
    byte[] signature = sig.toByteArray();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] digest = md.digest(signature);
        return BaseEncoding.base16().lowerCase().encode(digest);
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
}

添加到请求标题:

java.net.URL url = new URL(REQUEST_URL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
    connection.setDoInput(true);
    connection.setDoOutput(true);

    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    connection.setRequestProperty("Accept", "application/json");

    // add package name to request header
    String packageName = mActivity.getPackageName();
    connection.setRequestProperty("X-Android-Package", packageName);
    // add SHA certificate to request header
    String sig = getSignature(mActivity.getPackageManager(), packageName);
    connection.setRequestProperty("X-Android-Cert", sig);
    connection.setRequestMethod("POST");

    // ADD YOUR REQUEST BODY HERE
    // ....................
} catch (Exception e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
}

您可以看到完整的答案here

享受编码:)