码迷,mamicode.com
首页 > 移动开发 > 详细

android支付宝 KeyFactory PrivateKey

时间:2015-09-18 18:58:19      阅读:662      评论:0      收藏:0      [点我收藏+]

标签:

public class SignUtils {


private static final String ALGORITHM = "RSA";


private static final String SIGN_ALGORITHMS = "SHA1WithRSA";


private static final String DEFAULT_CHARSET = "UTF-8";


public static String sign(String content, String privateKey) {

try {

PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(

Base64.decode(privateKey));

KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);

PrivateKey priKey = keyf.generatePrivate(priPKCS8);


java.security.Signature signature = java.security.Signature

.getInstance(SIGN_ALGORITHMS);


signature.initSign(priKey);

signature.update(content.getBytes(DEFAULT_CHARSET));


byte[] signed = signature.sign();


return Base64.encode(signed);

} catch (Exception e) {

e.printStackTrace();

}


return null;

}


}


第一开始,调用KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);报错。如下:

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag


KeyFactory keyf = KeyFactory.getInstance(ALGORITHM, "BC");  加入了“BC”报如下错误:

com.android.org.bouncycastle.jcajce.provider.asymmetric.util.ExtendedInvalidKeySpecException: unable to process key spec: java.lang.ClassCastException: com.android.org.bouncycastle.asn1.DLSequence cannot be cast to com.android.org.bouncycastle.asn1.ASN1Integer


最终因为传入私钥错误。需要重新生成私钥:

私钥的格式大约是这样:技术分享


android支付宝 KeyFactory PrivateKey

标签:

原文地址:http://my.oschina.net/u/1395670/blog/508251

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!