Search in sources :

Example 1 with OpenSSHPrivateKeySpec

use of org.bouncycastle.jcajce.spec.OpenSSHPrivateKeySpec in project hutool by looly.

the class SM2Test method getPublicKeyByPrivateKeyTest.

@Test
public void getPublicKeyByPrivateKeyTest() {
    // issue#I38SDP,openSSL生成的PKCS#1格式私钥
    String priKey = "MHcCAQEEIE29XqAFV/rkJbnJzCoQRJLTeAHG2TR0h9ZCWag0+ZMEoAoGCCqBHM9VAYItoUQDQgAESkOzNigIsH5ehFvr9y" + "QNQ66genyOrm+Q4umCA4aWXPeRzmcTAWSlTineiReTFN2lqor2xaulT8u3a4w3AM/F6A==";
    PrivateKey privateKey = KeyUtil.generatePrivateKey("sm2", new OpenSSHPrivateKeySpec(SecureUtil.decode(priKey)));
    final ECPrivateKeyParameters privateKeyParameters = ECKeyUtil.toPrivateParams(privateKey);
    final SM2 sm2 = new SM2(privateKeyParameters, ECKeyUtil.getPublicParams(privateKeyParameters));
    String src = "Sm2Test";
    byte[] data = sm2.encrypt(src, KeyType.PublicKey);
    byte[] sign = sm2.sign(src.getBytes(StandardCharsets.UTF_8));
    Assert.assertTrue(sm2.verify(src.getBytes(StandardCharsets.UTF_8), sign));
    byte[] dec = sm2.decrypt(data, KeyType.PrivateKey);
    Assert.assertArrayEquals(dec, src.getBytes(StandardCharsets.UTF_8));
}
Also used : ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) PrivateKey(java.security.PrivateKey) OpenSSHPrivateKeySpec(org.bouncycastle.jcajce.spec.OpenSSHPrivateKeySpec) SM2(cn.hutool.crypto.asymmetric.SM2) Test(org.junit.Test)

Aggregations

SM2 (cn.hutool.crypto.asymmetric.SM2)1 PrivateKey (java.security.PrivateKey)1 ECPrivateKeyParameters (org.bouncycastle.crypto.params.ECPrivateKeyParameters)1 OpenSSHPrivateKeySpec (org.bouncycastle.jcajce.spec.OpenSSHPrivateKeySpec)1 Test (org.junit.Test)1