美文网首页
JCA 实践记录——Signature

JCA 实践记录——Signature

作者: JSON_NULL | 来源:发表于2019-01-25 12:08 被阅读10次

    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);
    

    支持的算法

    1. MD2withRSA
    2. MD5withRSA
    3. SHA1withRSA
    4. SHA224withRSA
    5. SHA256withRSA
    6. SHA384withRSA
    7. SHA512withRSA
    8. MD5andSHA1withRSA
    9. SHA1withDSA
    10. NONEwithDSA
    11. SHA224withDSA
    12. SHA256withDSA
    13. NONEwithECDSA
    14. SHA1withECDSA
    15. SHA224withECDSA
    16. SHA256withECDSA
    17. SHA384withECDSA
    18. SHA512withECDSA

    相关文章

      网友评论

          本文标题:JCA 实践记录——Signature

          本文链接:https://www.haomeiwen.com/subject/myrmjqtx.html