(1)生成簽名:對源文件的「數字摘要」,使用私鑰加密,生成「加密數字摘要」;java
(2)驗證簽名:對「加密數字摘要」經過公鑰進行解密,生成「數字摘要2」,比較「數字摘要」與「數字摘要2」,結果相同則簽名驗證經過。算法
概念:帶有「公鑰」和「私鑰」的「消息摘要」算法,是「非對稱加密算法」和「消息摘要」算法的結合體加密
私鑰簽名,公鑰驗證code
RSASignature開發
DSASignatureget
ECDSASignature(需Bouncy Castle)it
驗證數據完整性io
認證數據來源ast
抗否定class
如Android App開發者簽名
import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class RSASignatureUtil { public static final String KEY_ALGORITHM = "RSA";//密鑰算法 public static final String SIGN_ALGORITHM = "MD5withRSA";//簽名算法:MD2withRSA,SHA1WithRSA,SHA256withRSA,SHA384withRSA,SHA512withRSA /** * 初始化RSA公鑰私鑰 */ public static KeyPair initKey() throws Exception{ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGenerator.initialize(1024); return keyPairGenerator.generateKeyPair(); } /** * 簽名(原數據,私鑰 2要素) */ public static byte[] sign(byte[] data, PrivateKey privateKey) throws Exception{ PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey priKey = keyFactory.generatePrivate(keySpec); Signature signature = Signature.getInstance(SIGN_ALGORITHM); signature.initSign(priKey); signature.update(data);//設置要計算的數據 return signature.sign(); } /** * 校驗簽名(元數據,公鑰,簽名 三要素) */ public static boolean valid(byte[] data, byte[] publicKey, byte[] sign) throws Exception{ KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); PublicKey pubKey = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGN_ALGORITHM); signature.initVerify(pubKey); signature.update(data); return signature.verify(sign); } public static void main(String[] args) throws Exception { String data = "123456"; KeyPair keyPair = initKey(); byte[] sign = sign(data.getBytes(),keyPair.getPrivate()); boolean isValid = valid(data.getBytes(),keyPair.getPublic().getEncoded(),sign); System.out.println(isValid); } }