java.security.Signature 是JCA中提供签名和验签服务器的类。
实例化
Signature没有公开的构造方法,所以只能调用其静态方法getInstace进行实现化。这个方法有多个重载如下:
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);此方法需要一个字符串作为参数,用于说明使用哪个签名/验签算法。
初始化
Signature 类提供了两个初始化方法(initSign/initVerify)分别用于签名和验签。
//签名初始化
public final void initSign(PrivateKey privateKey)
        throws InvalidKeyException; 
//签名初始化
public final void initSign(PrivateKey privateKey, SecureRandom random)
        throws InvalidKeyException;
//验签初始化
public final void initVerify(PublicKey publicKey)
        throws InvalidKeyException;
//签名初始化
public final void initVerify(Certificate certificate)
        throws InvalidKeyException
签名时需要使用私钥,而验签时需要使用公钥,所以在执行签名或验签算法之前需要使用私钥或公钥对Signature实例进行初始化。
注:验签时还可以使用证书,所以用于验签的Signature实例可以使用Certificate对象进行初始化。
update 方法 更新数据
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;
使用指定信息更新(待签/待验)数据;
签名和验签方法
// 签名方法
public final byte[] sign() throws SignatureException;
public final int sign(byte[] outbuf, int offset, int len)
    throws SignatureException;
无参方法直接返回签名后的结果,有参方法则是把签名结果按要求参数给定的byte数组之中。通常我们使用无参方法就足够了。
// 验签方法
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