java.security.Signature 是JCA中提供簽名和驗(yàn)簽服務(wù)器的類(lèi)。
實(shí)例化
Signature
沒(méi)有公開(kāi)的構(gòu)造方法,所以只能調(diào)用其靜態(tài)方法getInstace
進(jìn)行實(shí)現(xiàn)化。這個(gè)方法有多個(gè)重載如下:
public static Signature getInstance(String algorithm)
throws NoSuchAlgorithmException;
public static Signature getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException;
public static Signature getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException;
我們通常使用的是public static Signature getInstance(String algorithm)
;此方法需要一個(gè)字符串作為參數(shù),用于說(shuō)明使用哪個(gè)簽名/驗(yàn)簽算法。
初始化
Signature 類(lèi)提供了兩個(gè)初始化方法(initSign/initVerify)分別用于簽名和驗(yàn)簽。
//簽名初始化
public final void initSign(PrivateKey privateKey)
throws InvalidKeyException;
//簽名初始化
public final void initSign(PrivateKey privateKey, SecureRandom random)
throws InvalidKeyException;
//驗(yàn)簽初始化
public final void initVerify(PublicKey publicKey)
throws InvalidKeyException;
//簽名初始化
public final void initVerify(Certificate certificate)
throws InvalidKeyException
簽名時(shí)需要使用私鑰,而驗(yàn)簽時(shí)需要使用公鑰,所以在執(zhí)行簽名或驗(yàn)簽算法之前需要使用私鑰或公鑰對(duì)Signature
實(shí)例進(jìn)行初始化。
注:驗(yàn)簽時(shí)還可以使用證書(shū),所以用于驗(yàn)簽的Signature
實(shí)例可以使用Certificate
對(duì)象進(jìn)行初始化。
update 方法 更新數(shù)據(jù)
public final void update(byte b) throws SignatureException;
public final void update(byte[] data) throws SignatureException;
public final void update(byte[] data, int off, int len)
throws SignatureException;
public final void update(ByteBuffer data) throws SignatureException;
使用指定信息更新(待簽/待驗(yàn))數(shù)據(jù);
簽名和驗(yàn)簽方法
// 簽名方法
public final byte[] sign() throws SignatureException;
public final int sign(byte[] outbuf, int offset, int len)
throws SignatureException;
無(wú)參方法直接返回簽名后的結(jié)果,有參方法則是把簽名結(jié)果按要求參數(shù)給定的byte數(shù)組之中。通常我們使用無(wú)參方法就足夠了。
// 驗(yàn)簽方法
public final boolean verify(byte[] signature) throws SignatureException;
public final boolean verify(byte[] signature, int offset, int length);
支持的算法
- MD2withRSA
- MD5withRSA
- SHA1withRSA
- SHA224withRSA
- SHA256withRSA
- SHA384withRSA
- SHA512withRSA
- MD5andSHA1withRSA
- SHA1withDSA
- NONEwithDSA
- SHA224withDSA
- SHA256withDSA
- NONEwithECDSA
- SHA1withECDSA
- SHA224withECDSA
- SHA256withECDSA
- SHA384withECDSA
- SHA512withECDSA