java.security.KeyPairGenerator Java Examples

The following examples show how to use java.security.KeyPairGenerator. 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: DHKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
DHEPossession(DHECredentials credentials, SecureRandom random) {
    try {
        KeyPairGenerator kpg =
                JsseJce.getKeyPairGenerator("DiffieHellman");
        kpg.initialize(credentials.popPublicKey.getParams(), random);
        KeyPair kp = generateDHKeyPair(kpg);
        if (kp == null) {
            throw new RuntimeException("Could not generate DH keypair");
        }
        privateKey = kp.getPrivate();
        publicKey = (DHPublicKey)kp.getPublic();
    } catch (GeneralSecurityException gse) {
        throw new RuntimeException(
                "Could not generate DH keypair", gse);
    }

    this.namedGroup = credentials.namedGroup;
}
 
Example #2
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider. <p> All private key operations
 * will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
  this.provider = provider;

  final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance
      (provider, secureRandom);
  final KeyPair keyPair = keyPairGen.generateKeyPair();

  this.privKey = keyPair.getPrivate();

  final PublicKey pubKey = keyPair.getPublic();
  if (pubKey instanceof BCECPublicKey) {
    pub = ((BCECPublicKey) pubKey).getQ();
  } else if (pubKey instanceof ECPublicKey) {
    pub = extractPublicKey((ECPublicKey) pubKey);
  } else {
    throw new AssertionError(
        "Expected Provider " + provider.getName() +
            " to produce a subtype of ECPublicKey, found " +
            pubKey.getClass());
  }
}
 
Example #3
Source File: GenerateKeypair.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(512);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }

        // test genKeyPair
        kpair = kpg.genKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
Example #4
Source File: GenerateKeypair.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(512);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }

        // test genKeyPair
        kpair = kpg.genKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
Example #5
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceAccountWithScopeNotToJwt() throws Exception {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
  @SuppressWarnings("deprecation")
  ServiceAccountCredentials credentials = new ServiceAccountCredentials(
      null, "[email protected]", pair.getPrivate(), null, Arrays.asList("somescope")) {
    @Override
    public AccessToken refreshAccessToken() {
      return token;
    }
  };

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);
  assertEquals(1, runPendingRunnables());

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  assertArrayEquals(new String[]{"Bearer allyourbase"},
      Iterables.toArray(authorization, String.class));
}
 
Example #6
Source File: FinalizeHalf.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void test(String algo, Provider provider, boolean priv,
        Consumer<Key> method) throws Exception {
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(algo, provider);
    } catch (NoSuchAlgorithmException nsae) {
        return;
    }

    System.out.println("Checking " + provider.getName() + ", " + algo);

    KeyPair pair = generator.generateKeyPair();
    Key key = priv ? pair.getPrivate() : pair.getPublic();

    pair = null;
    for (int i = 0; i < 32; ++i) {
        System.gc();
    }

    try {
        method.accept(key);
    } catch (ProviderException pe) {
        failures++;
    }
}
 
Example #7
Source File: AttestationProtocol.java    From Auditor with MIT License 6 votes vote down vote up
static void generateKeyPair(final String algorithm, final KeyGenParameterSpec spec)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException, IOException {
    // Handle RuntimeExceptions caused by a broken keystore. A common issue involves users
    // unlocking the device and wiping the encrypted TEE attestation keys from the persist
    // partition. Additionally, some non-CTS compliant devices or operating systems have a
    // non-existent or broken implementation. No one has reported these uncaught exceptions,
    // presumably because they know their device or OS is broken, but the crash reports are
    // being spammed to the Google Play error collection and causing it to think the app is
    // unreliable.
    try {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm,
                "AndroidKeyStore");
        keyPairGenerator.initialize(spec);
        keyPairGenerator.generateKeyPair();
    } catch (final ProviderException e) {
        throw new IOException(e);
    }
}
 
Example #8
Source File: KeyStoreUtils.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void generateOldKeyPair() throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
        // Generate the RSA key pairs
        if (!keyStore.containsAlias(KEY_ALIAS)) {
            // Generate a key pair for encryption
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 30);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(KEY_ALIAS)
                    .setSubject(new X500Principal("CN=" + KEY_ALIAS))
                    .setSerialNumber(BigInteger.TEN)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
//            KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", AndroidKeyStore);
            kpg.initialize(spec);
            kpg.generateKeyPair();
        }
    }
 
Example #9
Source File: TestCipherKeyWrapperTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void wrapperPublicPriviteKeyTest(Provider p, String[] algorithms)
        throws NoSuchAlgorithmException, InvalidKeyException,
        NoSuchPaddingException, IllegalBlockSizeException,
        InvalidAlgorithmParameterException {
    for (String algo : algorithms) {
        // Key pair generated
        System.out.println("Generate key pair (algorithm: " + algo
                + ", provider: " + p.getName() + ")");
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
        kpg.initialize(512);
        KeyPair kp = kpg.genKeyPair();
        // key generated
        String algoWrap = "DES";
        KeyGenerator kg = KeyGenerator.getInstance(algoWrap, p);
        Key key = kg.generateKey();
        wrapTest(algo, algoWrap, key, kp.getPrivate(), Cipher.PRIVATE_KEY,
                false);
        wrapTest(algo, algoWrap, key, kp.getPublic(), Cipher.PUBLIC_KEY,
                false);
    }
}
 
Example #10
Source File: SensitiveDataCodecTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeyEncodeDecode() throws IOException {
  MockitoAnnotations.initMocks(this);
  KeyPair keyPair;
  try {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyPairGenerator.initialize(2048, random);
    keyPair = keyPairGenerator.generateKeyPair();
  } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
    throw new IOException(e);
  }

  when(sensitiveDataCodecHelperMock.getKeyPair()).thenReturn(keyPair);
  SensitiveDataCodec sensitiveDataCodec = new SensitiveDataCodec(sensitiveDataCodecHelperMock);
  String readable = "testObfEn&c$o#de";
  String encrypt = sensitiveDataCodec.encodeData(readable, SecurityLevel.ENCRYPTED);
  String decrypt = sensitiveDataCodec.decodeData(encrypt);
  assertEquals(readable, decrypt);
  assertThat(encrypt, startsWith("pkc:"));
}
 
Example #11
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 *
 * <p>All private key operations will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
    this.provider = provider;

    final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
    final KeyPair keyPair = keyPairGen.generateKeyPair();

    this.privKey = keyPair.getPrivate();

    final PublicKey pubKey = keyPair.getPublic();
    if (pubKey instanceof BCECPublicKey) {
        pub = ((BCECPublicKey) pubKey).getQ();
    } else if (pubKey instanceof ECPublicKey) {
        pub = extractPublicKey((ECPublicKey) pubKey);
    } else {
        throw new AssertionError(
                "Expected Provider " + provider.getName()
                        + " to produce a subtype of ECPublicKey, found "
                        + pubKey.getClass());
    }
}
 
Example #12
Source File: RSAUtil.java    From RairDemo with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化密钥
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> initKey() throws Exception {
    // 通过算法类型获得对应的密钥生成器
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    // 指定密钥对的长度
    keyPairGen.initialize(1024);

    // 获取密钥对
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // 公钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    // 私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    Map<String, Object> keyMap = new HashMap<String, Object>(2);

    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);

    return keyMap;
}
 
Example #13
Source File: GenerateKeypair.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(512);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }

        // test genKeyPair
        kpair = kpg.genKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
Example #14
Source File: KeyStoreCipher.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
private void initGeneratorWithKeyPairGeneratorSpec(KeyPairGenerator generator, String alias) throws InvalidAlgorithmParameterException {
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.YEAR, 200);

    KeyPairGeneratorSpec.Builder builder = new KeyPairGeneratorSpec
            .Builder(context)
            .setAlias(alias)
            .setKeySize(KEY_SIZE)
            .setSerialNumber(BigInteger.ONE)
            .setSubject(new X500Principal("CN=" + alias + " CA Certificate"))
            .setStartDate(startDate.getTime())
            .setEndDate(endDate.getTime());

    generator.initialize(builder.build());
}
 
Example #15
Source File: GenerationTests.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static KeyPair generateKeyPair(SignatureMethod sm)
        throws NoSuchAlgorithmException {
    KeyPairGenerator keygen;
    switch (sm.getAlgorithm()) {
        case SignatureMethod.DSA_SHA1:
            keygen = KeyPairGenerator.getInstance("DSA");
            break;
        case SignatureMethod.RSA_SHA1:
            keygen = KeyPairGenerator.getInstance("RSA");
            break;
        default:
            throw new RuntimeException("Unsupported signature algorithm");
    }

    SecureRandom random = new SecureRandom();
    keygen.initialize(1024, random);
    return keygen.generateKeyPair();
}
 
Example #16
Source File: DHKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
DHEPossession(NamedGroup namedGroup, SecureRandom random) {
    try {
        KeyPairGenerator kpg =
                JsseJce.getKeyPairGenerator("DiffieHellman");
        DHParameterSpec params =
                (DHParameterSpec)namedGroup.getParameterSpec();
        kpg.initialize(params, random);
        KeyPair kp = generateDHKeyPair(kpg);
        if (kp == null) {
            throw new RuntimeException("Could not generate DH keypair");
        }
        privateKey = kp.getPrivate();
        publicKey = (DHPublicKey)kp.getPublic();
    } catch (GeneralSecurityException gse) {
        throw new RuntimeException(
                "Could not generate DH keypair", gse);
    }

    this.namedGroup = namedGroup;
}
 
Example #17
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 * <p>
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
    this.provider = provider;

    final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
    final KeyPair keyPair = keyPairGen.generateKeyPair();

    this.privKey = keyPair.getPrivate();

    final PublicKey pubKey = keyPair.getPublic();
    this.publicKey = keyPair.getPublic();
    if (pubKey instanceof BCECPublicKey) {
        pub = ((BCECPublicKey) pubKey).getQ();
    } else if (pubKey instanceof ECPublicKey) {
        pub = extractPublicKey((ECPublicKey) pubKey);
    } else {
        throw new AssertionError(
                "Expected Provider " + provider.getName() +
                        " to produce a subtype of ECPublicKey, found " + pubKey.getClass());
    }
}
 
Example #18
Source File: ECDHKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
ECDHEPossession(NamedGroup namedGroup, SecureRandom random) {
    try {
        KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
        ECGenParameterSpec params =
                (ECGenParameterSpec)namedGroup.getParameterSpec();
        kpg.initialize(params, random);
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        publicKey = (ECPublicKey)kp.getPublic();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(
            "Could not generate ECDH keypair", e);
    }

    this.namedGroup = namedGroup;
}
 
Example #19
Source File: CredentialSafe.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Generate a new ES256 keypair (COSE algorithm -7, ECDSA + SHA-256 over the NIST P-256 curve).
 *
 * @param alias The alias used to identify this keypair in the keystore. Needed to use key
 *              in the future.
 * @return The KeyPair object representing the newly generated keypair.
 * @throws VirgilException
 */
private KeyPair generateNewES256KeyPair(String alias) throws VirgilException {
    KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec(CURVE_NAME))
            .setDigests(KeyProperties.DIGEST_SHA256)
            .setUserAuthenticationRequired(this.authenticationRequired) // fingerprint or similar
            .setUserConfirmationRequired(false) // TODO: Decide if we support Android Trusted Confirmations
            .setInvalidatedByBiometricEnrollment(false)
            .setIsStrongBoxBacked(this.strongboxRequired)
            .build();
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE_TYPE);
        keyPairGenerator.initialize(spec);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        throw new VirgilException("couldn't generate key pair: " + e.toString());
    }
}
 
Example #20
Source File: WeEventFileClient.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public void genPemFile(String filePath) throws BrokerException {
    validateLocalFile(filePath);
    try {
        BouncyCastleProvider prov = new BouncyCastleProvider();
        Security.addProvider(prov);

        ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE_TYPE);
        KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM, prov.getName());
        generator.initialize(ecSpec, new SecureRandom());
        KeyPair pair = generator.generateKeyPair();
        String pubKey = pair.getPublic().toString();
        String account = HEX_HEADER + pubKey.substring(pubKey.indexOf("[") + 1, pubKey.indexOf("]")).replace(":", "");

        PemFile privatePemFile = new PemFile(pair.getPrivate(), PRIVATE_KEY_DESC);
        PemFile publicPemFile = new PemFile(pair.getPublic(), PUBLIC_KEY_DESC);


        System.out.println(filePath + PATH_SEPARATOR + account + PRIVATE_KEY_SUFFIX);
        privatePemFile.write(filePath + PATH_SEPARATOR + account + PRIVATE_KEY_SUFFIX);
        publicPemFile.write(filePath + PATH_SEPARATOR + account + PUBLIC_KEY_SUFFIX);
    } catch (IOException | NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        log.error("generate pem file error");
        throw new BrokerException(ErrorCode.FILE_GEN_PEM_BC_FAILED);
    }
}
 
Example #21
Source File: RSAEncrypt.java    From mcg-helper with Apache License 2.0 6 votes vote down vote up
/**
 * 随机生成密钥对
 */
public static String genKeyPair() {
    // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    KeyPairGenerator keyPairGen = null;
    try {
        keyPairGen = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
    	logger.error(e.getMessage());
    }
    // 初始化密钥对生成器,密钥大小为96-2048位
    keyPairGen.initialize(1024, new SecureRandom());
    // 生成一个密钥对,保存在keyPair中
    KeyPair keyPair = keyPairGen.generateKeyPair();
    // 得到私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    // 得到公钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    // 得到公钥字符串
    String publicKeyString = Base64.encode(publicKey.getEncoded());
    // 得到私钥字符串
    String privateKeyString = Base64.encode(privateKey.getEncoded());
    // 将密钥对写入到文件
    return "{publicKey:" + publicKeyString + ", privateKey:" + privateKeyString + "}";
}
 
Example #22
Source File: SolarisShortDSA.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    for (int i=0; i<10000; i++) {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        KeyPair kp = kpg.generateKeyPair();
        DSAPrivateKey dpk = (DSAPrivateKey)kp.getPrivate();
        int len = dpk.getX().bitLength();
        if (len <= 152) {
            if (!use(kp)) {
                String os = System.getProperty("os.name");
                // Solaris bug, update the following line once it's fixed
                if (os.equals("SunOS")) {
                    throw new IllegalStateException(
                            "Don't panic. This is a Solaris bug");
                } else {
                    throw new RuntimeException("Real test failure");
                }
            }
            break;
        }
    }
}
 
Example #23
Source File: SpecTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        int size = 0;

        if (args.length >= 1) {
            size = Integer.parseInt(args[0]);
        } else {
            throw new RuntimeException("Missing keysize to test with");
        }

        BigInteger publicExponent
                = (args.length >= 2) ? new BigInteger(args[1]) : RSAKeyGenParameterSpec.F4;

        System.out.println("Running test with key size: " + size
                + " and public exponent: " + publicExponent);

        KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
        kpg1.initialize(new RSAKeyGenParameterSpec(size, publicExponent));
        if (!specTest(kpg1.generateKeyPair(), publicExponent)) {
            throw new RuntimeException("Test failed.");
        }
    }
 
Example #24
Source File: GenerateJWTTest.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 6 votes vote down vote up
@Test
public void generateJWT(TestReporter reporter) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    Assumptions.assumeTrue(kpg.getAlgorithm().equals("RSA"));
    kpg.initialize(2048);
    reporter.publishEntry("Created RSA key pair generator of size 2048");
    KeyPair keyPair = kpg.generateKeyPair();
    reporter.publishEntry("Created RSA key pair");
    Assumptions.assumeTrue(keyPair != null, "KeyPair is not null");
    PublicKey publicKey = keyPair.getPublic();
    reporter.publishEntry("RSA.publicKey", publicKey.toString());
    PrivateKey privateKey = keyPair.getPrivate();
    reporter.publishEntry("RSA.privateKey", privateKey.toString());

    assertAll("GenerateJWTTest",
        () -> assertEquals("X.509", publicKey.getFormat()),
        () -> assertEquals("PKCS#8", privateKey.getFormat()),
        () -> assertEquals("RSA", publicKey.getAlgorithm()),
        () -> assertEquals("RSA", privateKey.getAlgorithm())
    );
}
 
Example #25
Source File: ECKeySecp256k1.java    From aion with MIT License 6 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 *
 * <p>All private key operations will use the provider.
 */
public ECKeySecp256k1(Provider provider, SecureRandom secureRandom) {
    this.provider = provider;

    final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
    final KeyPair keyPair = keyPairGen.generateKeyPair();

    this.privKey = keyPair.getPrivate();

    final PublicKey pubKey = keyPair.getPublic();
    if (pubKey instanceof BCECPublicKey) {
        pub = ((BCECPublicKey) pubKey).getQ();
    } else if (pubKey instanceof ECPublicKey) {
        pub = extractPublicKey((ECPublicKey) pubKey);
    } else {
        throw new AssertionError(
                "Expected Provider "
                        + provider.getName()
                        + " to produce a subtype of ECPublicKey, found "
                        + pubKey.getClass());
    }
}
 
Example #26
Source File: EciesEncryptionTest.java    From protect with MIT License 6 votes vote down vote up
@Test
public void testEncryptDecrypt() throws Exception {

	final String name = "secp256r1";

	// NOTE just "EC" also seems to work here
	final KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDH", BouncyCastleProvider.PROVIDER_NAME);
	kpg.initialize(new ECGenParameterSpec(name));

	// Key pair to store public and private key
	final KeyPair keyPair = kpg.generateKeyPair();

	// Message to encrypt
	byte[] message = "hello".getBytes(StandardCharsets.UTF_8);

	// Encrypt
	final BigInteger r = EciesEncryption.generateR();
	byte[] encrypted = EciesEncryption.encrypt(message, r, keyPair.getPublic());

	// Decrypt
	byte[] decrypted = EciesEncryption.decrypt(encrypted, keyPair.getPrivate());
	System.out.println("Decrypted message: " + new String(decrypted));

	Assert.assertArrayEquals(message, decrypted);

}
 
Example #27
Source File: AuthenticationServiceJwtImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
private void generateRSAKeyPairs(File rsocketKeysDir) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair keyPair = kpg.generateKeyPair();
    Key pub = keyPair.getPublic();
    Key pvt = keyPair.getPrivate();
    try (OutputStream out = new FileOutputStream(new File(rsocketKeysDir, "jwt_rsa.key"))) {
        out.write(pvt.getEncoded());
    }
    try (OutputStream out2 = new FileOutputStream(new File(rsocketKeysDir, "jwt_rsa.pub"))) {
        out2.write(pub.getEncoded());
    }
}
 
Example #28
Source File: KeyStoreUtilsTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void generateKeysAndCertificates() throws NoSuchAlgorithmException, CertificateException {
    caCertKeyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    issuedCertificateKeyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();

    caCertificate = CertificateUtils.generateSelfSignedX509Certificate(caCertKeyPair, "CN=testca,O=Apache,OU=NiFi", SIGNING_ALGORITHM, DURATION_DAYS);
    issuedCertificate = CertificateUtils.generateIssuedCertificate("CN=testcert,O=Apache,OU=NiFi", issuedCertificateKeyPair.getPublic(), caCertificate, caCertKeyPair, SIGNING_ALGORITHM,
            DURATION_DAYS);
}
 
Example #29
Source File: TestDSAGenParameterSpec.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkParam(AlgorithmParameters param,
        DSAGenParameterSpec genParam) throws InvalidParameterSpecException,
        NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException {
    String algorithm = param.getAlgorithm();
    if (!algorithm.equalsIgnoreCase(ALGORITHM_NAME)) {
        throw new RuntimeException(
                "Unexpected type of parameters: " + algorithm);
    }

    DSAParameterSpec spec = param.getParameterSpec(DSAParameterSpec.class);
    int valueL = spec.getP().bitLength();
    int strengthP = genParam.getPrimePLength();
    if (strengthP != valueL) {
        System.out.printf("P: Expected %d but actual %d%n", strengthP,
                valueL);
        throw new RuntimeException("Wrong P strength");
    }

    int valueN = spec.getQ().bitLength();
    int strengthQ = genParam.getSubprimeQLength();
    if (strengthQ != valueN) {
        System.out.printf("Q: Expected %d but actual %d%n", strengthQ,
                valueN);
        throw new RuntimeException("Wrong Q strength");
    }

    if (genParam.getSubprimeQLength() != genParam.getSeedLength()) {
        System.out.println("Defaut seed length should be the same as Q.");
        throw new RuntimeException("Wrong seed length");
    }

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_NAME,
            PROVIDER_NAME);
    keyGen.initialize(spec);
}
 
Example #30
Source File: JwtSignTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignWithInvalidRSAKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    PrivateKey key = keyPairGenerator.generateKeyPair().getPrivate();
    try {
        Jwt.claims().sign(key);
        Assert.fail("JwtSignatureException is expected due to the invalid key size");
    } catch (JwtSignatureException ex) {
        Assert.assertEquals("SRJWT05002: A key of size 2048 bits or larger MUST be used with the 'RS256' algorithm",
                ex.getMessage());
    }
}