foxlog
4/22/2018 - 12:41 PM

java 曲线椭圆加密算法 KeyPairGenerator

java 曲线椭圆加密算法 KeyPairGenerator

//曲线椭圆加密算法
public static void ec() throws InvalidKeyException, SignatureException, NoSuchAlgorithmException {
    //Create a key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    keyGen.initialize(256, random);

    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();

    System.out.println("private key: " + Arrays.toString(privateKey.getEncoded()));
    System.out.println("public key: " + Arrays.toString(publicKey.getEncoded()));



    String input = "hello world";

    //签名算法
    Signature signer = Signature.getInstance("SHA256withECDSA");

    //用私钥初始化签名
    signer.initSign(privateKey);
    //用签名更新输入
    signer.update(input.getBytes());
    byte[] sign = signer.sign();

    //打印得到的签名, 可以将此签名传给第三方
    System.out.println("input is:  " + input);
    System.out.println("Sign: " + Arrays.toString(sign));


    //第三方用公钥初始化,用签名做验证, 返回true表示验证正确
    Signature verifier = Signature.getInstance("SHA256withECDSA");
    verifier.initVerify(publicKey);

    //第三方的数据abc,用签名来验证是否和数据一致
    String input_again = "hello world";
    verifier.update(input_again.getBytes());
    boolean checkResult = verifier.verify(sign);
    System.out.println("Sign result : " + checkResult);
}