org.bouncycastle.crypto.AsymmetricCipherKeyPair Java Examples
The following examples show how to use
org.bouncycastle.crypto.AsymmetricCipherKeyPair.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SslClientCertificateImplTest.java From hivemq-community-edition with Apache License 2.0 | 7 votes |
private KeyPair createKeyPair() throws InvalidKeySpecException, NoSuchAlgorithmException { final RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 80)); final AsymmetricCipherKeyPair keypair = gen.generateKeyPair(); final RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic(); final RSAPrivateCrtKeyParameters privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate(); final PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic( new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent())); final PrivateKey privKey = KeyFactory.getInstance("RSA").generatePrivate( new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(), privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(), privateKey.getDQ(), privateKey.getQInv())); return new KeyPair(pubKey, privKey); }
Example #2
Source File: SM2UtilTest.java From gmhelper with Apache License 2.0 | 6 votes |
@Test public void testEncodeSM2CipherToDER_C1C2C3() { try { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); byte[] encryptedData = SM2Util.encrypt(Mode.C1C2C3, pubKey, SRC_DATA); byte[] derCipher = SM2Util.encodeSM2CipherToDER(Mode.C1C2C3, encryptedData); FileUtil.writeFile("target/derCipher_c1c2c3.dat", derCipher); byte[] decryptedData = SM2Util.decrypt(Mode.C1C2C3, priKey, SM2Util.decodeDERSM2Cipher(Mode.C1C2C3, derCipher)); if (!Arrays.equals(decryptedData, SRC_DATA)) { Assert.fail(); } Assert.assertTrue(true); } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } }
Example #3
Source File: SM2UtilTest.java From gmhelper with Apache License 2.0 | 6 votes |
@Test public void testEncodeSM2CipherToDER() { try { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); byte[] encryptedData = SM2Util.encrypt(pubKey, SRC_DATA); byte[] derCipher = SM2Util.encodeSM2CipherToDER(encryptedData); FileUtil.writeFile("target/derCipher.dat", derCipher); byte[] decryptedData = SM2Util.decrypt(priKey, SM2Util.decodeDERSM2Cipher(derCipher)); if (!Arrays.equals(decryptedData, SRC_DATA)) { Assert.fail(); } Assert.assertTrue(true); } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } }
Example #4
Source File: NativeRSAVectors.java From jna-gmp with Apache License 2.0 | 6 votes |
private static void generateTestVector(int rsaKeyBits, int suffix) throws Exception { AsymmetricCipherKeyPair pair = generateKeyPair(rsaKeyBits); RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) pair.getPrivate(); byte[] message = new byte[rsaKeyBits / 8]; SECURE_RANDOM.nextBytes(message); // Clear the top bit to ensure it fits. message[0] &= 0x7F; RSAEngine encoder = new RSAEngine(); encoder.init(true, pair.getPrivate()); byte[] signed = encoder.processBlock(message, 0, message.length); RSAEngine decoder = new RSAEngine(); decoder.init(false, pair.getPublic()); byte[] decoded = decoder.processBlock(signed, 0, message.length); Assert.assertArrayEquals(message, decoded); System.out.println("public static final TestVector VECTOR" + suffix + " = "); new TestVector(new BigInteger(1, message), new BigInteger(1, signed), (RSAPrivateCrtKeyParameters) pair.getPrivate()).printJavaConstructorFor(); System.out.println(); }
Example #5
Source File: AccountServiceImpl.java From javasdk with GNU Lesser General Public License v3.0 | 6 votes |
@Override public Account genAccount(Algo algo, String password) { byte[] address; byte[] publicKey; byte[] privateKey; ECKey ecKey; AsymmetricCipherKeyPair keyPair; if (algo.isSM()) { keyPair = SM2Util.generateKeyPair(); ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); BigInteger privateKeyBI = ecPriv.getD(); publicKey = ecPub.getQ().getEncoded(false); privateKey = Account.encodePrivateKey(ByteUtil.biConvert32Bytes(privateKeyBI), algo, password); address = HashUtil.sha3omit12(publicKey); return new SMAccount(ByteUtil.toHex(address), ByteUtil.toHex(publicKey), ByteUtil.toHex(privateKey), Version.V4, algo, keyPair); } else { ecKey = new ECKey(new SecureRandom()); address = ecKey.getAddress(); publicKey = ecKey.getPubKey(); privateKey = Account.encodePrivateKey(ecKey.getPrivKeyBytes(), algo, password); return new ECAccount(ByteUtil.toHex(address), ByteUtil.toHex(publicKey), ByteUtil.toHex(privateKey), Version.V4, algo, ecKey); } }
Example #6
Source File: SM2UtilTest.java From gmhelper with Apache License 2.0 | 6 votes |
@Test public void testSM2KeyGen2() { try { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); System.out.println("Pri Hex:" + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase()); System.out.println("Pub Point Hex:" + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase()); } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } }
Example #7
Source File: TransactionUtil.java From chain33-sdk-java with BSD 2-Clause "Simplified" License | 6 votes |
/** * @description 创建私钥和公钥 * * @return 私钥 */ public static byte[] generatorPrivateKey() { int length = 0; byte[] privateKey; do { ECKeyPairGenerator gen = new ECKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(); X9ECParameters secnamecurves = SECNamedCurves.getByName("secp256k1"); ECDomainParameters ecParams = new ECDomainParameters(secnamecurves.getCurve(), secnamecurves.getG(), secnamecurves.getN(), secnamecurves.getH()); ECKeyGenerationParameters keyGenParam = new ECKeyGenerationParameters(ecParams, secureRandom); gen.init(keyGenParam); AsymmetricCipherKeyPair kp = gen.generateKeyPair(); ECPrivateKeyParameters privatekey = (ECPrivateKeyParameters) kp.getPrivate(); privateKey = privatekey.getD().toByteArray(); length = privatekey.getD().toByteArray().length; } while (length != 32); return privateKey; }
Example #8
Source File: BCECUtilTest.java From gmhelper with Apache License 2.0 | 6 votes |
@Test public void testECPrivateKeyPKCS8() { try { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic(); byte[] pkcs8Bytes = BCECUtil.convertECPrivateKeyToPKCS8(priKeyParams, pubKeyParams); BCECPrivateKey priKey = BCECUtil.convertPKCS8ToECPrivateKey(pkcs8Bytes); byte[] sign = SM2Util.sign(priKey, GMBaseTest.WITH_ID, GMBaseTest.SRC_DATA); System.out.println("SM2 sign with withId result:\n" + ByteUtils.toHexString(sign)); boolean flag = SM2Util.verify(pubKeyParams, GMBaseTest.WITH_ID, GMBaseTest.SRC_DATA, sign); if (!flag) { Assert.fail("[withId] verify failed"); } } catch (Exception e) { e.printStackTrace(); Assert.fail(); } }
Example #9
Source File: BouncyCastleV1CryptoProvider.java From paseto with MIT License | 6 votes |
@Override public KeyPair rsaGenerate() { RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator(); keyGen.init(new RSAKeyGenerationParameters(E, new SecureRandom(), RSA_KEY_SIZE, PrimeCertaintyCalculator.getDefaultCertainty(RSA_KEY_SIZE))); AsymmetricCipherKeyPair pair = keyGen.generateKeyPair(); RSAKeyParameters pub = (RSAKeyParameters) pair.getPublic(); RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) pair.getPrivate(); // As in BCRSAPrivateKey / BCRSAPublicKey AlgorithmIdentifier algo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); byte[] publicKey = KeyUtil.getEncodedSubjectPublicKeyInfo(algo, new RSAPublicKey(pub.getModulus(), pub.getExponent())); byte[] privateKey = KeyUtil.getEncodedPrivateKeyInfo(algo, new RSAPrivateKey(priv.getModulus(), priv.getPublicExponent(), priv.getExponent(), priv.getP(), priv.getQ(), priv.getDP(), priv.getDQ(), priv.getQInv())); return new KeyPair(privateKey, publicKey); }
Example #10
Source File: LocalIdentity.java From ts3j with Apache License 2.0 | 6 votes |
/** * Generates a new identity with a given security level target. * @param securityLevel security level to generate for (may take time) * @return local identity with given security level * @throws GeneralSecurityException */ public static LocalIdentity generateNew(int securityLevel) throws GeneralSecurityException { ECNamedCurveParameterSpec ecp = ECNamedCurveTable.getParameterSpec("prime256v1"); ECDomainParameters domainParams = new ECDomainParameters(ecp.getCurve(), ecp.getG(), ecp.getN(), ecp.getH(), ecp.getSeed()); ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom()); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(keyGenParams); AsymmetricCipherKeyPair keyPair = generator.generateKeyPair(); ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic(); LocalIdentity localIdentity = load(publicKey.getQ().normalize(), privateKey.getD()); localIdentity.improveSecurity(securityLevel); return localIdentity; }
Example #11
Source File: Cipher.java From nuls with MIT License | 5 votes |
public ECPoint initEnc(SM2 sm2, ECPoint userKey) { AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair(); ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate(); ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic(); BigInteger k = ecpriv.getD(); ECPoint c1 = ecpub.getQ(); this.p2 = userKey.multiply(k); reset(); return c1; }
Example #12
Source File: Sm2KeyPairImpl.java From littleca with Apache License 2.0 | 5 votes |
public Sm2KeyPairImpl(boolean selfgen) { SecureRandom random = new SecureRandom(); ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS, random); ECKeyPairGenerator keyGen = new ECKeyPairGenerator(); keyGen.init(keyGenerationParams); AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); ECDomainParameters domainParams = priKey.getParameters(); ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(), domainParams.getN(), domainParams.getH()); BCECPublicKey bcecPublicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec, BouncyCastleProvider.CONFIGURATION); publicKey = new Sm2PublicKeyImpl(bcecPublicKey); privateKey = new Sm2PrivateKeyImpl(new BCECPrivateKey(ALGO_NAME_EC, priKey, bcecPublicKey, spec, BouncyCastleProvider.CONFIGURATION)); }
Example #13
Source File: BCECUtil.java From littleca with Apache License 2.0 | 5 votes |
/** * 生成ECC密钥对 * * @return ECC密钥对 */ public static AsymmetricCipherKeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random) { ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParameters, random); ECKeyPairGenerator keyGen = new ECKeyPairGenerator(); keyGen.init(keyGenerationParams); return keyGen.generateKeyPair(); }
Example #14
Source File: SM2.java From julongchain with Apache License 2.0 | 5 votes |
/** * sm2密钥对生成 * * @return */ public SM2KeyPair generateKeyPair() { ECKeyGenerationParameters ecKeyGenerationParameters = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom()); ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.init(ecKeyGenerationParameters); AsymmetricCipherKeyPair kp = keyPairGenerator.generateKeyPair(); ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) kp.getPrivate(); ECPublicKeyParameters ecpub = (ECPublicKeyParameters) kp.getPublic(); BigInteger privateKey = ecpriv.getD(); ECPoint publicKey = ecpub.getQ(); return new SM2KeyPair(publicKey.getEncoded(false), privateKey.toByteArray()); }
Example #15
Source File: ECKey.java From nuls-v2 with MIT License | 5 votes |
/** * Generates an entirely new keypair with the given {@link SecureRandom} object. Point compression is used so the * resulting public key will be 33 bytes (32 for the co-ordinate and 1 byte to represent the y bit). */ public ECKey(SecureRandom secureRandom) { ECKeyPairGenerator generator = new ECKeyPairGenerator(); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, secureRandom); generator.init(keygenParams); AsymmetricCipherKeyPair keypair = generator.generateKeyPair(); ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate(); ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic(); priv = privParams.getD(); pub = new LazyECPoint(CURVE.getCurve(), pubParams.getQ().getEncoded(true)); creationTimeSeconds = System.currentTimeMillis(); }
Example #16
Source File: EncryptionUtilTest.java From Hive2Hive with MIT License | 5 votes |
@Test @Ignore public void testPureLightweightBouncyCastle() throws IOException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, DataLengthException, IllegalStateException, InvalidCipherTextException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException { long startTime = System.currentTimeMillis(); Security.addProvider(new BouncyCastleProvider()); // generate RSA keys RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); gen.init(new RSAKeyGenerationParameters(new BigInteger("10001", 16), new SecureRandom(), 2048, 80)); AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); // some data where first entry is 0 byte[] data = { 10, 122, 12, 127, 35, 58, 87, 56, -6, 73, 10, -13, -78, 4, -122, -61 }; // encrypt data asymmetrically AsymmetricBlockCipher cipher = new RSAEngine(); cipher = new PKCS1Encoding(cipher); cipher.init(true, keyPair.getPublic()); byte[] rsaEncryptedData = cipher.processBlock(data, 0, data.length); Assert.assertFalse(Arrays.equals(data, rsaEncryptedData)); // decrypt data asymmetrically cipher.init(false, keyPair.getPrivate()); byte[] dataBack = cipher.processBlock(rsaEncryptedData, 0, rsaEncryptedData.length); assertTrue(Arrays.equals(data, dataBack)); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; logger.debug("elapsed time = {}", elapsedTime); }
Example #17
Source File: BouncyCastleCrypto.java From fabric-api-archive with Apache License 2.0 | 5 votes |
@Override public byte[] createNewPrivateKey() { ECKeyPairGenerator generator = new ECKeyPairGenerator(); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(domain, secureRandom); generator.init(keygenParams); AsymmetricCipherKeyPair keypair = generator.generateKeyPair(); ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate(); return privParams.getD().toByteArray(); }
Example #18
Source File: BouncyCastleCrypto.java From fabric-api with Apache License 2.0 | 5 votes |
@Override public byte[] createNewPrivateKey() { ECKeyPairGenerator generator = new ECKeyPairGenerator(); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(domain, secureRandom); generator.init(keygenParams); AsymmetricCipherKeyPair keypair = generator.generateKeyPair(); ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate(); return privParams.getD().toByteArray(); }
Example #19
Source File: Sign1MessageTest.java From COSE-JAVA with BSD 3-Clause "New" or "Revised" License | 5 votes |
@BeforeClass public static void setUpClass() throws CoseException { X9ECParameters p = NISTNamedCurves.getByName("P-256"); ECDomainParameters parameters = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, null); pGen.init(genParam); AsymmetricCipherKeyPair p1 = pGen.generateKeyPair(); keyPublic = (ECPublicKeyParameters) p1.getPublic(); keyPrivate = (ECPrivateKeyParameters) p1.getPrivate(); byte[] rgbX = keyPublic.getQ().normalize().getXCoord().getEncoded(); byte[] rgbY = keyPublic.getQ().normalize().getYCoord().getEncoded(); boolean signY = true; byte[] rgbD = keyPrivate.getD().toByteArray(); CBORObject key = CBORObject.NewMap(); key.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2); key.Add(KeyKeys.EC2_Curve.AsCBOR(), KeyKeys.EC2_P256); key.Add(KeyKeys.EC2_X.AsCBOR(), rgbX); key.Add(KeyKeys.EC2_Y.AsCBOR(), rgbY); cnKeyPublic = new OneKey(key); key = CBORObject.NewMap(); key.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2); key.Add(KeyKeys.EC2_Curve.AsCBOR(), KeyKeys.EC2_P256); key.Add(KeyKeys.EC2_X.AsCBOR(), rgbX); key.Add(KeyKeys.EC2_Y.AsCBOR(), rgbY); cnKeyPublicCompressed = new OneKey(key); key = CBORObject.NewMap(); key.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2); key.Add(KeyKeys.EC2_Curve.AsCBOR(), KeyKeys.EC2_P256); key.Add(KeyKeys.EC2_D.AsCBOR(), rgbD); cnKeyPrivate = new OneKey(key); }
Example #20
Source File: BCECUtil.java From jiguang-java-client-common with MIT License | 5 votes |
/** * 生成ECC密钥对 * * @return ECC密钥对 */ public static AsymmetricCipherKeyPair generateKeyPairParameter(ECDomainParameters domainParameters, SecureRandom random) { ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParameters, random); ECKeyPairGenerator keyGen = new ECKeyPairGenerator(); keyGen.init(keyGenerationParams); return keyGen.generateKeyPair(); }
Example #21
Source File: SecP256K1KeyGenerator.java From nem.core with MIT License | 5 votes |
@Override public KeyPair generateKeyPair() { final ECKeyPairGenerator generator = new ECKeyPairGenerator(); final ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(SecP256K1Curve.secp256k1().getParams(), RANDOM); generator.init(keyGenParams); final AsymmetricCipherKeyPair keyPair = generator.generateKeyPair(); final ECPrivateKeyParameters privateKeyParams = (ECPrivateKeyParameters)keyPair.getPrivate(); final PrivateKey privateKey = new PrivateKey(privateKeyParams.getD()); return new KeyPair(privateKey, CryptoEngines.secp256k1Engine()); }
Example #22
Source File: ECKeyPair.java From bop-bitcoin-client with Apache License 2.0 | 5 votes |
public static ECKeyPair createNew (boolean compressed) { ECKeyPairGenerator generator = new ECKeyPairGenerator (); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters (domain, secureRandom); generator.init (keygenParams); AsymmetricCipherKeyPair keypair = generator.generateKeyPair (); ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate (); ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic (); ECKeyPair k = new ECKeyPair (); k.priv = privParams.getD (); k.compressed = compressed; k.pub = pubParams.getQ ().getEncoded (compressed); return k; }
Example #23
Source File: ECKeyPair.java From WalletCordova with GNU Lesser General Public License v2.1 | 5 votes |
public static ECKeyPair createNew (boolean compressed) { ECKeyPairGenerator generator = new ECKeyPairGenerator (); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters (domain, secureRandom); generator.init (keygenParams); AsymmetricCipherKeyPair keypair = generator.generateKeyPair (); ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate (); ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic (); ECKeyPair k = new ECKeyPair (); k.priv = privParams.getD (); k.compressed = compressed; k.pub = pubParams.getQ ().getEncoded (compressed); return k; }
Example #24
Source File: CryptographicUtilities.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
public static AsymmetricCipherKeyPair generateRsaKeyPair(int keyStrength) throws Exception { Security.addProvider(new BouncyCastleProvider()); try { RSAKeyPairGenerator generator = new RSAKeyPairGenerator(); generator.init(new RSAKeyGenerationParameters(RSAKeyGenParameterSpec.F4, SecureRandom.getInstance("SHA1PRNG"), keyStrength, 80)); AsymmetricCipherKeyPair keyPair = generator.generateKeyPair(); return keyPair; } catch (Exception e) { throw new Exception("Cannot create RSA keypair", e); } }
Example #25
Source File: SM2UtilTest.java From gmhelper with Apache License 2.0 | 5 votes |
@Test public void testEncryptAndDecrypt_C1C2C3() { try { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); System.out.println("Pri Hex:" + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase()); System.out.println("Pub Point Hex:" + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase()); byte[] encryptedData = SM2Util.encrypt(Mode.C1C3C2, pubKey, SRC_DATA_48B); System.out.println("SM2 encrypt result:\n" + ByteUtils.toHexString(encryptedData)); byte[] decryptedData = SM2Util.decrypt(Mode.C1C3C2, priKey, encryptedData); System.out.println("SM2 decrypt result:\n" + ByteUtils.toHexString(decryptedData)); if (!Arrays.equals(decryptedData, SRC_DATA_48B)) { Assert.fail(); } } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } }
Example #26
Source File: SM2UtilTest.java From gmhelper with Apache License 2.0 | 5 votes |
@Test public void testEncryptAndDecrypt() { try { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); System.out.println("Pri Hex:" + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase()); System.out.println("Pub Point Hex:" + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase()); byte[] encryptedData = SM2Util.encrypt(pubKey, SRC_DATA_24B); System.out.println("SM2 encrypt result:\n" + ByteUtils.toHexString(encryptedData)); byte[] decryptedData = SM2Util.decrypt(priKey, encryptedData); System.out.println("SM2 decrypt result:\n" + ByteUtils.toHexString(decryptedData)); if (!Arrays.equals(decryptedData, SRC_DATA_24B)) { Assert.fail(); } } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } }
Example #27
Source File: SM2UtilTest.java From gmhelper with Apache License 2.0 | 5 votes |
@Test public void testSignAndVerify() { try { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); System.out.println("Pri Hex:" + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase()); System.out.println("Pub X Hex:" + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase()); System.out.println("Pub Point Hex:" + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase()); byte[] sign = SM2Util.sign(priKey, WITH_ID, SRC_DATA); System.out.println("SM2 sign with withId result:\n" + ByteUtils.toHexString(sign)); byte[] rawSign = SM2Util.decodeDERSM2Sign(sign); sign = SM2Util.encodeSM2SignToDER(rawSign); System.out.println("SM2 sign with withId result:\n" + ByteUtils.toHexString(sign)); boolean flag = SM2Util.verify(pubKey, WITH_ID, SRC_DATA, sign); if (!flag) { Assert.fail("verify failed"); } sign = SM2Util.sign(priKey, SRC_DATA); System.out.println("SM2 sign without withId result:\n" + ByteUtils.toHexString(sign)); flag = SM2Util.verify(pubKey, SRC_DATA, sign); if (!flag) { Assert.fail("verify failed"); } } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } }
Example #28
Source File: SM2KeyExchangeUtilTest.java From gmhelper with Apache License 2.0 | 5 votes |
@Test public void testCalculateKeyWithConfirmation() { try { AsymmetricCipherKeyPair initiatorStaticKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters initiatorStaticPriv = (ECPrivateKeyParameters) initiatorStaticKp.getPrivate(); ECPublicKeyParameters initiatorStaticPub = (ECPublicKeyParameters) initiatorStaticKp.getPublic(); AsymmetricCipherKeyPair initiatorEphemeralKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters initiatorEphemeralPriv = (ECPrivateKeyParameters) initiatorEphemeralKp.getPrivate(); ECPublicKeyParameters initiatorSEphemeralPub = (ECPublicKeyParameters) initiatorEphemeralKp.getPublic(); AsymmetricCipherKeyPair responderStaticKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters responderStaticPriv = (ECPrivateKeyParameters) responderStaticKp.getPrivate(); ECPublicKeyParameters responderStaticPub = (ECPublicKeyParameters) responderStaticKp.getPublic(); AsymmetricCipherKeyPair responderEphemeralKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters responderEphemeralPriv = (ECPrivateKeyParameters) responderEphemeralKp.getPrivate(); ECPublicKeyParameters responderSEphemeralPub = (ECPublicKeyParameters) responderEphemeralKp.getPublic(); //第一步应该是交换临时公钥等信息 //第二步响应方生成密钥和验证信息 SM2KeyExchangeUtil.ExchangeResult responderResult = SM2KeyExchangeUtil.calculateKeyWithConfirmation( false, KEY_BITS, null, responderStaticPriv, responderEphemeralPriv, RESPONDER_ID, initiatorStaticPub, initiatorSEphemeralPub, INITIATOR_ID); //第三步发起方生成密钥和验证消息,并验证响应方的验证消息 SM2KeyExchangeUtil.ExchangeResult initiatorResult = SM2KeyExchangeUtil.calculateKeyWithConfirmation( true, KEY_BITS, responderResult.getS1(), initiatorStaticPriv, initiatorEphemeralPriv, INITIATOR_ID, responderStaticPub, responderSEphemeralPub, RESPONDER_ID); //第四步响应方验证发起方的验证消息 if (!SM2KeyExchangeUtil.responderConfirm(responderResult.getS2(), initiatorResult.getS2())) { Assert.fail(); } } catch (Exception ex) { Assert.fail(); } }
Example #29
Source File: SM2KeyExchangeUtilTest.java From gmhelper with Apache License 2.0 | 5 votes |
@Test public void testCaculateKey() { try { AsymmetricCipherKeyPair initiatorStaticKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters initiatorStaticPriv = (ECPrivateKeyParameters) initiatorStaticKp.getPrivate(); ECPublicKeyParameters initiatorStaticPub = (ECPublicKeyParameters) initiatorStaticKp.getPublic(); AsymmetricCipherKeyPair initiatorEphemeralKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters initiatorEphemeralPriv = (ECPrivateKeyParameters) initiatorEphemeralKp.getPrivate(); ECPublicKeyParameters initiatorSEphemeralPub = (ECPublicKeyParameters) initiatorEphemeralKp.getPublic(); AsymmetricCipherKeyPair responderStaticKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters responderStaticPriv = (ECPrivateKeyParameters) responderStaticKp.getPrivate(); ECPublicKeyParameters responderStaticPub = (ECPublicKeyParameters) responderStaticKp.getPublic(); AsymmetricCipherKeyPair responderEphemeralKp = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters responderEphemeralPriv = (ECPrivateKeyParameters) responderEphemeralKp.getPrivate(); ECPublicKeyParameters responderSEphemeralPub = (ECPublicKeyParameters) responderEphemeralKp.getPublic(); //实际应用中应该是通过网络交换临时公钥 byte[] k1 = SM2KeyExchangeUtil.calculateKey(true, KEY_BITS, initiatorStaticPriv, initiatorEphemeralPriv, INITIATOR_ID, responderStaticPub, responderSEphemeralPub, RESPONDER_ID); byte[] k2 = SM2KeyExchangeUtil.calculateKey(false, KEY_BITS, responderStaticPriv, responderEphemeralPriv, RESPONDER_ID, initiatorStaticPub, initiatorSEphemeralPub, INITIATOR_ID); if (!Arrays.equals(k1, k2)) { Assert.fail(); } } catch (Exception ex) { Assert.fail(); } }
Example #30
Source File: SM2PreprocessSignerTest.java From gmhelper with Apache License 2.0 | 5 votes |
@Test public void test() throws CryptoException { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); SM2PreprocessSigner signer = new SM2PreprocessSigner(); CipherParameters pwr = new ParametersWithRandom(priKey, new SecureRandom()); signer.init(true, pwr); byte[] eHash1 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length); byte[] sign1 = signer.generateSignature(eHash1); signer = new SM2PreprocessSigner(); signer.init(false, pubKey); byte[] eHash2 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length); if (!Arrays.equals(eHash1, eHash2)) { Assert.fail(); } if (!signer.verifySignature(eHash1, sign1)) { Assert.fail(); } }