【发布时间】: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[]