android 签名验证

来源:互联网 发布:服务器装mysql 编辑:程序博客网 时间:2024/06/09 18:15
/** * 签名算法 */public static final String SIGNATURE_ALGORITHM = "MD5withRSA";/** * RSA最大解密密文大小 */public static final String KEY_ALGORITHM = "RSA";public static String sign(byte[] data, String privateKey) throws Exception {    byte[] keyBytes = Base64Utils.decode(privateKey);    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);    signature.initSign(privateK);    signature.update(data);    //Base64Utils.encode(signature.sign())    byte[] sign = signature.sign();    String s = conver16HexStr(sign);    return s;}

public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64Utils.decode(sign));
}
/**
* 读取密钥信息
*
* @param in
* @return
* @throws IOException
*/
public static String readKey(InputStream in) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null)
{
if (readLine.charAt(0) == ‘-‘)
{
continue;
} else
{
sb.append(readLine);
sb.append(‘\r’);
}
}

    return sb.toString();} InputStream inPrivate = getResources().getAssets().open("pkcs8_rsa_private_key.pem");String s1 = RSAUtils.readKey(inPrivate);

http://blog.csdn.net/mq2856992713/article/details/52587254
http://www.jianshu.com/p/8747d01a0450
http://blog.csdn.net/jdsjlzx/article/details/41441147

原创粉丝点击