Digital signature sample code (JAVA)

Sample program


import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *Sample for signature and signature verification with ECDSA 160bit
 */
public class ECDSASignature {

    public static void main(String argv[]){
        signatureTest();
    }
    
    public static void signatureTest(){

        /**
         *Issue key pair
         */
        KeyPairGenerator keyPairGenerator = null;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("EC");
        } catch (NoSuchAlgorithmException ex) {
            return;
        }
        SecureRandom secureRandom = new SecureRandom();
        keyPairGenerator.initialize(160, secureRandom);
        KeyPair pair = keyPairGenerator.generateKeyPair();
        Key publicKey = pair.getPublic();
        Key privateKey = pair.getPrivate();        
        
        //For the time being, just a string
        String hako = "Qiita is a technical information sharing service for programmers.";
        
        /**
         *Sign with private key (ECDSA 160bit)
         */
        byte[] sign = null;
        try {
            Signature signatureSign = null;
            signatureSign = Signature.getInstance("NONEwithECDSA");
            signatureSign.initSign((PrivateKey)privateKey, secureRandom);
            signatureSign.update(hako.getBytes());
            sign = signatureSign.sign();
            
            System.out.println("sign: " + new String(sign));

        } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException ex) {
            Logger.getLogger(ECDSASignature.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        /**
         *Verify signature with public key
         */
        Signature signatureVerify = null;
        try {
            signatureVerify = Signature.getInstance("NONEwithECDSA");
            signatureVerify.initVerify((PublicKey)publicKey);
            signatureVerify.update(hako.getBytes());
            boolean verifyResult = signatureVerify.verify(sign);
            System.out.println(verifyResult ? "Signature OK" : "Signature NG");
            
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            Logger.getLogger(ECDSASignature.class.getName()).log(Level.SEVERE, null, e);
        }
        
    }

}

Execution result


sign:(Omitted)
Signature OK

Recommended Posts

Digital signature sample code (JAVA)
Java sample code 02
Java sample code 03
Java sample code 04
Java sample code 01
Java parallelization code sample collection
Java 9 new features and sample code
Sample code using Minio from Java
Script Java code
Java code TIPS
[Java] Generics sample
Selenium sample (Java)
Java GUI sample
Sample code collection for Azure Java development
Java character code
[Java] Explanation of Strategy pattern (with sample code)
Apache beam sample code
[Java] Holiday judgment sample
[Java] logback slf4j sample
Sample code to convert List to List <String> in Java Stream
Sample code for log output by Java + SLF4J + Logback
Java test code method collection
[Windows] Java code is garbled
Sample code to parse date and time with Java SimpleDateFormat
Java in Visual Studio Code
Java standard log output sample
Write Java8-like code in Java8
Selenium Sample Reservation Form (Java)
Implement XML signature in Java
How to manage Java code automatically generated by jOOQ & Flyway sample
Sample code to call the Yahoo! Local Search API in Java
Sample code that uses the Mustache template engine JMustache in Java
Guess the character code in Java
Code Java from Emacs with Eclim
Java Spring environment in vs Code
Java 15 implementation and VS Code preferences
About signature authentication with java 1st
[Java] Boilerplate code elimination using Lombok
Java build with mac vs code
Arbitrary string creation code by Java
Execute packaged Java code with commands
A simple sample callback in Java
Java source code reading java.lang.Math class
[Java] Boilerplate code elimination using Lombok 2
BloomFilter description and implementation sample (JAVA)
[Java] Date period duplication check sample
EXCEL file update sample with JAVA
Java development environment (Mac, VS Code)
[Android] Convert Android Java code to Kotlin
Sample vending machine made in Java
Basic structure of Java source code
Sample code to get key JDBC type values in Java + H2 Database
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Java EE 8 (using NetBeans IDE 8.2) starting from sample code Part 1 Environment construction
Minimum configuration sample to automatically release Lambda by Java with Code pipeline