Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.0 kB
2
Indexable
Never
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class ECDSASample {

    public static void main(String[] args) throws Exception {
        // Generate key pair
        KeyPair keyPair = generateKeyPair();

        // Message to be signed
        String message = "Hello, ECDSA!";

        // Sign the message
        String signature = sign(message, keyPair.getPrivate());

        // Verify the signature
        boolean isVerified = verify(message, signature, keyPair.getPublic());

        System.out.println("Original Message: " + message);
        System.out.println("Signature: " + signature);
        System.out.println("Signature Verified: " + isVerified);
    }

    // Generate key pair
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
        ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
        keyGen.initialize(ecSpec, new SecureRandom());
        return keyGen.generateKeyPair();
    }

    // Sign a message using private key
    public static String sign(String message, PrivateKey privateKey) throws Exception {
        Signature ecdsaSign = Signature.getInstance("SHA256withECDSA");
        ecdsaSign.initSign(privateKey);
        ecdsaSign.update(message.getBytes());
        byte[] signatureBytes = ecdsaSign.sign();
        return Base64.getEncoder().encodeToString(signatureBytes);
    }

    // Verify a signature using public key
    public static boolean verify(String message, String signature, PublicKey publicKey) throws Exception {
        Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA");
        ecdsaVerify.initVerify(publicKey);
        ecdsaVerify.update(message.getBytes());
        byte[] signatureBytes = Base64.getDecoder().decode(signature);
        return ecdsaVerify.verify(signatureBytes);
    }
}
Leave a Comment