数字签名算法:DSA,使用EC生成的私钥签名,EC生成的公钥验证

CallmeZhe 2019-01-18

private static PrivateKey privateKey = null;
private static PublicKey publicKey = null;

@BeforeClass
public static void init() {
    KeyPairGenerator keyPairGenerator = null;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance("EC");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    keyPairGenerator.initialize(256, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    privateKey = keyPair.getPrivate(); // sun.security.ec.ECPrivateKeyImpl
    publicKey = keyPair.getPublic(); // sun.security.ec.ECPublicKeyImpl

    byte[] privateKeyEncoded = ((Key) privateKey).getEncoded();
    byte[] publicKeyEncoded = ((Key) publicKey).getEncoded();
    System.out.println("private key: " + Base64.byteArrayToBase64(privateKeyEncoded));
    System.out.println("public key: " + Base64.byteArrayToBase64(publicKeyEncoded));
}
@org.junit.Test
public void test() {
    String message = "13120983870";
    System.out.println(message);

    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("EC");
    } catch (NoSuchAlgorithmException e) {
        Assert.fail("no such algorithm: " + e.getMessage());
    }

    // 签名
    Signature signature = null;
    try {
        signature = Signature.getInstance("NONEwithECDSA");
    } catch (NoSuchAlgorithmException e) {
        Assert.fail("no such algorithm: " + e.getMessage());
    }
    try {
        signature.initSign(privateKey);
    } catch (InvalidKeyException e) {
        Assert.fail("invalid key: " + e.getMessage());
    }

    byte[] sign = null;
    try {
        signature.update(message.getBytes());
        sign = signature.sign();
    } catch (SignatureException e) {
        Assert.fail("signature: " + e.getMessage());
    }
    System.out.println("signature: " + Base64.byteArrayToBase64(sign));

    // 验证
    try {
        signature.initVerify(publicKey);
    } catch (InvalidKeyException e) {
        Assert.fail("invalid key: " + e.getMessage());
    }

    try {
        signature.update(message.getBytes());
        boolean result = signature.verify(sign);
        Assert.assertTrue(result);
    } catch (SignatureException e) {
        Assert.fail("signature: " + e.getMessage());
    }
}
private key: MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCCo4Ko3RblXEVy85V4P1ODvLUOAXb2sKvtJmkOV5/HUHQ==
public key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE6NjtyqaRPShUnTn3OrM9CNnIxKHf3yWv4iFR/LPCcCTfnzGvIb3n/9REss3wjbeBNpZBFStPsYbY+iPWXA3ASw==
13120983870
signature: MEUCIQCse/HImkyfODAdG8Xz0CKc3MSwsLGjY7ObKnlrgMKudAIgWDXfeJ9I9OtwqUuzIDwc148M9gDCXVYikB+0OGNlvBw=

相关推荐