带示例的 Java Signature initSign() 方法


initSign() 方法初始化该对象进行签名。如果再次使用不同的参数调用此方法,它将否定此调用的效果。

下面让我们来看一个示例:

示例

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Scanner;
public class Main {
   public static void main(String args[]) throws Exception {
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
      //Generate the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      //Getting the privatekey from the key pair
      PrivateKey privKey = pair.getPrivate();
      //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withDSA");
      //Initializing the signature
      sign.initSign(privKey);
      byte[] bytes = "Hello how are you".getBytes();
      //Adding data to the signature
      sign.update(bytes);
      //Calculating the signature
      byte[] signature = sign.sign();
      //Initializing the signature
      sign.initVerify(pair.getPublic());
      sign.update(bytes);
      //Verifying the signature
      boolean bool = sign.verify(signature);
      if(bool) {
         System.out.println("Signature verified");
      } else {
         System.out.println("Signature failed");
      }
   }
}

输出

Signature verified

更新于: 2019-09-23

343 次浏览

开启您的 职业生涯

完成课程以获取认证

开始
广告