1忽冻、簽名代碼
/**
* 簽名算法
*/
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
/**
* RSA簽名
* @param content 待簽名數據
* @param privateKey 私鑰
* @param encode 字符集編碼
* @return 簽名值
*/
public static String sign(String content, String privateKey, String encode) {
try{
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update( content.getBytes(encode));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2首量、驗簽代碼
/**
* 校驗緩存控制文件的簽名是否合法
* @param content 待簽名數據
* @param sign 簽名值
* @param publicKey 公鑰
* @return 失敗時蔼两,返回false休溶。
*/
public static boolean verifySignature(String content,String sign,String publicKey){
if(null == fileText || null == signText || "".equals(fileText) || "".equals(signText)){
return false;
}
try {
byte[] pubKeyText = publicKey.getBytes();
byte[] signTextByte = signText.getBytes();
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(Base64.decode(pubKeyText, Base64.DEFAULT));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);
byte[] signed = Base64.decode(signTextByte, Base64.DEFAULT);
Signature signatureChecker = Signature.getInstance("SHA1WithRSA");
signatureChecker.initVerify(pubKey);
signatureChecker.update(content.getBytes());
// 驗證簽名是否正常
return signatureChecker.verify(signed);
} catch (Exception e) {
MuLog.error(TAG, e);
return false;
}
}