【问题标题】:Signing a string using a private key, RSA-SHA1 signature and than md5 it in Android在 Android 中使用私钥、RSA-SHA1 签名和 md5 对字符串进行签名
【发布时间】:2013-06-06 04:10:26
【问题描述】:

我需要使用 RSA-SHA1 签名和来自 .PFX 证书的私钥对字符串进行签名。 这是我的代码:

String rawString = "1234567890";

byte[] signed = null;

FileInputStream cert = new FileInputStream("/sdcard/cert.pfx");

KeyStore keyStore = KeyStore.getInstance("pkcs12");
keyStore.load(cert, "cert_password".toCharArray());

String alias = keyStore.aliases().nextElement();
PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, "cert_password".toCharArray());

Signature instance = Signature.getInstance("SHA1withRSA");
instance.initSign((PrivateKey)privateKey);
instance.update(rawString.getBytes());
signed = instance.sign();

TextView mTextView = (TextView) findViewById(R.id.signed_message);
mTextView.setText(md5(bytes2String(signed)));

我确实得到了一个漂亮的 MD5,但是,我也在 PHP 中做同样的事情,我使用 PHP 得到的结果与 Android 中的不同。我知道 PHP 是正确的...那么 Android 版本有什么问题?

我注意到,如果我使用 new String(signed) 而不是 bytes2String(signed) 或者即使我使用 signed.toString(),Android 结果会有所不同

我将它用于 MD5:https://stackoverflow.com/a/4846511/1176497

和来自 (Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher) 的 bytes2String:

private static String bytes2String(byte[] bytes) {
    StringBuilder string = new StringBuilder();
    for (byte b : bytes) {
        String hexString = Integer.toHexString(0x00FF & b);
        string.append(hexString.length() == 1 ? "0" + hexString : hexString);
    }
    return string.toString();
}

【问题讨论】:

  • 字节数组和字符串之间的转换总是依赖于Charset
  • 是的,谢谢...问题出在转换中。事实证明我根本不需要转换 byte[],因为 md5 需要 byte[]

标签: android rsa md5 sha1


【解决方案1】:

我想通了……

我正在使用的 md5 函数需要一个字符串,但将其转换为 byte[]... 因为我已经有了 byte[],所以无需转换它!

现在我得到了与 PHP 相同的结果 :)

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2011-02-02
    • 2011-01-22
    相关资源
    最近更新 更多