数字签名算法:DSA,使用EC生成的私钥签名,EC生成的公钥验证
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=
相关推荐
燕哥带你学算法 2020-06-11
natloc 2020-06-10
dushine00 2020-02-03
yedaoxiaodi 2019-12-29
Happyunlimited 2019-12-09
luohui 2019-11-10
CallmeZhe 2019-01-18
HeavyIndustry 2019-02-19
算法魔功 2016-04-05
HeavyIndustry 2019-02-19
闫新宇 2011-12-09
ustbfym 2011-11-24
tuonioooo 2011-10-08
zhuyonge 2011-07-26
ThinkBigWinBig 2020-06-06
gongruitao 2020-05-16
STchaoL 2020-05-11
rein0 2020-01-29
风吹夏天 2019-12-27