Java Code Examples for java.security.KeyPairGenerator

The following are top voted examples for showing how to use java.security.KeyPairGenerator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: PACE   File: ValueSignerTest.java   View source code 8 votes vote down vote up
private void signatureTest(ValueSigner signer, KeyPairGenerator generator) throws Exception {
  byte[] data = "HELLO".getBytes();
  Signature signature = signer.getInstance(null);
  KeyPair pair = generator.generateKeyPair();

  signature.initSign(pair.getPrivate());
  signature.update(data);
  byte[] digest = signature.sign();

  assertThat("digest has a value", TestUtils.wrap(digest), is(not(emptyArray())));

  signature.initVerify(pair.getPublic());
  signature.update(data);
  assertThat("verification succeeds", signature.verify(digest), is(true));

  switch (signer) {
    case RSA_PKCS1:
      break;

    default:
      signature.initSign(pair.getPrivate());
      signature.update(data);
      assertThat("signatures correctly use random padding", signature.sign(), not(equalTo(digest)));
  }
}
 
Example 2
Project: AppCoins-ethereumj   File: ECKey.java   View source code 7 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 *
 * 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
Project: talchain   File: ECKey.java   View source code 7 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 *
 * 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 4
Project: AppCoins-ethereumj   File: ECKey.java   View source code 7 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 *
 * 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 5
Project: firebase-admin-java   File: FirebaseTokenFactoryTest.java   View source code 6 votes vote down vote up
@Test
public void checkSignatureForToken() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock);

  String jwt =
      tokenFactory.createSignedCustomAuthTokenForUser(
          USER_ID, EXTRA_CLAIMS, ISSUER, keys.getPrivate());

  FirebaseCustomAuthToken signedJwt = FirebaseCustomAuthToken.parse(FACTORY, jwt);
  assertEquals("RS256", signedJwt.getHeader().getAlgorithm());
  assertEquals(ISSUER, signedJwt.getPayload().getIssuer());
  assertEquals(ISSUER, signedJwt.getPayload().getSubject());
  assertEquals(USER_ID, signedJwt.getPayload().getUid());
  assertEquals(2L, signedJwt.getPayload().getIssuedAtTimeSeconds().longValue());

  assertTrue(TestUtils.verifySignature(signedJwt, ImmutableList.of(keys.getPublic())));
}
 
Example 6
Project: AppCoins-ethereumj   File: ECKeyTest.java   View source code 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testInvalidPrivateKey() throws Exception {
    new ECKey(
        Security.getProvider("SunEC"),
        KeyPairGenerator.getInstance("RSA").generateKeyPair().getPrivate(),
        ECKey.fromPublicOnly(pubKey).getPubKeyPoint());
    fail("Expecting an IllegalArgumentException for using an non EC private key");
}
 
Example 7
Project: GitHub   File: GeneratePubkeyActivity.java   View source code 6 votes vote down vote up
@Override
public void run() {
	SecureRandom random = new SecureRandom();

	// Work around JVM bug
	random.nextInt();
	random.setSeed(entropy);

	try {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(keyType);

		keyPairGen.initialize(numBits, random);

		listener.onGenerationSuccess(keyPairGen.generateKeyPair());
	} catch (Exception e) {
		listener.onGenerationError(e);
	}
}
 
Example 8
Project: bouncr   File: JsonWebTokenTest.java   View source code 6 votes vote down vote up
@Test
public void test() throws IOException, NoSuchAlgorithmException {
    EnkanSystem system = EnkanSystem.of(
            "jsonWebToken", new JsonWebToken(),
            "config", new BouncrConfiguration()
    ).relationships(
            component("jsonWebToken").using("config")
    );
    system.start();
    JsonWebToken jsonWebToken = (JsonWebToken)system.getComponent("jsonWebToken");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);
    KeyPair kp = keyGen.generateKeyPair();

    JwtHeader header = builder(new JwtHeader())
            .set(JwtHeader::setAlg, "RS256")
            .set(JwtHeader::setKid, "keyid")
            .build();
    JwtClaim payload = builder(new JwtClaim())
            .set(JwtClaim::setSub, "kawasima")
            .set(JwtClaim::setIss, "https://localhost:3002")
            .build();
    String sign = jsonWebToken.sign(payload, header, kp.getPrivate());
    System.out.println(sign);
}
 
Example 9
Project: openjdk-jdk10   File: SupportedDHKeys.java   View source code 6 votes vote down vote up
@Override
public void main(Provider provider) throws Exception {
    if (provider.getService("KeyPairGenerator", "DiffieHellman") == null) {
        System.out.println("No support of DH KeyPairGenerator, skipping");
        return;
    }

    for (SupportedKeySize keySize : SupportedKeySize.values()) {
        System.out.println("Checking " + keySize.primeSize + " ...");
        KeyPairGenerator kpg =
                KeyPairGenerator.getInstance("DiffieHellman", provider);
        kpg.initialize(keySize.primeSize);
        KeyPair kp = kpg.generateKeyPair();
        checkKeyPair(kp, keySize.primeSize, provider);

        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
        BigInteger p = publicKey.getParams().getP();
        BigInteger g = publicKey.getParams().getG();
        kpg.initialize(new DHParameterSpec(p, g));
        kp = kpg.generateKeyPair();
        checkKeyPair(kp, keySize.primeSize, provider);
    }
}
 
Example 10
Project: jdk8u-jdk   File: GenerateKeypair.java   View source code 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 11
Project: sensorhub-cloud-iot   File: MqttAuthentication.java   View source code 6 votes vote down vote up
/**
 * Generate a new RSA key pair entry in the Android Keystore by
 * using the KeyPairGenerator API. This creates both a KeyPair
 * and a self-signed certificate, both with the same alias
 */
private void generateAuthenticationKey() throws GeneralSecurityException {

  KeyPairGenerator kpg = KeyPairGenerator.getInstance(
      KeyProperties.KEY_ALGORITHM_RSA, keystoreName);
  kpg.initialize(new KeyGenParameterSpec.Builder(
      keyAlias,
      KeyProperties.PURPOSE_SIGN)
      .setKeySize(2048)
      .setCertificateSubject(new X500Principal("CN=unused"))
      .setDigests(KeyProperties.DIGEST_SHA256)
      .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
      .build());

  kpg.generateKeyPair();
}
 
Example 12
Project: wolfcrypt-jni   File: WolfCryptKeyPairGeneratorTest.java   View source code 6 votes vote down vote up
@Test
public void testKeyPairGeneratorEccMultipleInits()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    if (enabledCurves.size() > 0) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(0));

        kpg.initialize(ecSpec);
        kpg.initialize(ecSpec);
    }
}
 
Example 13
Project: wolfcrypt-jni   File: WolfCryptKeyPairGeneratorTest.java   View source code 6 votes vote down vote up
@Test
public void testKeyPairGeneratorEccInitializeWithKeySize()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    /* try initializing KPG for all supported key sizes */
    for (int i = 0; i < enabledKeySizes.size(); i++) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        kpg.initialize(enabledKeySizes.get(i));

        /* bad key size should fail */
        try {
            kpg.initialize(9999);
        } catch (WolfCryptException e) {}
    }
}
 
Example 14
Project: spring-web-jsflow   File: GeneratedKeyPairFactory.java   View source code 6 votes vote down vote up
@Override
protected KeyPair createInstance() throws Exception {
    if (secureRandom == null) {
        final SecureRandomFactory secureRandomFactory = new SecureRandomFactory();
        secureRandomFactory.setProvider(provider);
        secureRandomFactory.afterPropertiesSet();
        secureRandom = secureRandomFactory.createInstance();
    }
    final KeyPairGenerator kpg;
    if (provider == null) {
        kpg = KeyPairGenerator.getInstance(algorithm);
    } else {
        kpg = KeyPairGenerator.getInstance(algorithm, provider);
    }
    kpg.initialize(keySize, secureRandom);
    return kpg.generateKeyPair();
}
 
Example 15
Project: wolfcrypt-jni   File: WolfCryptKeyPairGeneratorTest.java   View source code 6 votes vote down vote up
@Test
public void testKeyPairGeneratorEccKeyGenAllCurves()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    /* try generating keys for all supported curves */
    for (int i = 0; i < enabledCurves.size(); i++) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(i));
        kpg.initialize(ecSpec);

        KeyPair kp = kpg.generateKeyPair();
    }
}
 
Example 16
Project: L2J-Global   File: GameServerTable.java   View source code 6 votes vote down vote up
/**
 * Inits the RSA keys.
 */
private void initRSAKeys()
{
	try
	{
		final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4));
		_keyPairs = new KeyPair[KEYS_SIZE];
		for (int i = 0; i < KEYS_SIZE; i++)
		{
			_keyPairs[i] = keyGen.genKeyPair();
		}
	}
	catch (Exception e)
	{
		LOGGER.severe(GameServerTable.class.getSimpleName() + ": Error loading RSA keys for Game Server communication!");
	}
}
 
Example 17
Project: PACE   File: LocalSignatureKeyContainerTest.java   View source code 6 votes vote down vote up
@Test
public void writeReadTest() throws Exception {
  for (ValueSigner signer : ValueSigner.values()) {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(signer.getKeyGenerationAlgorithm());
    if (signer == ValueSigner.ECDSA) {
      gen.initialize(256);
    } else {
      gen.initialize(1024);
    }

    KeyPair pair = gen.generateKeyPair();
    byte[] keyId = String.format("%s_%s", gen.getAlgorithm(), "test").getBytes(ENCODING_CHARSET);
    LocalSignatureKeyContainer container = new LocalSignatureKeyContainer(pair, keyId);

    File file = folder.newFile();
    FileWriter writer = new FileWriter(file);
    container.write(writer);
    writer.close();

    LocalSignatureKeyContainer container2 = LocalSignatureKeyContainer.read(new FileReader(file));
    assertThat("has matching keys", container2.getSigningKey().key.getEncoded(), equalTo(container.getSigningKey().key.getEncoded()));
    assertThat("has matching keys", container2.getSigningKey().id, equalTo(container.getSigningKey().id));
    assertThat("has matching keys", container2.getVerifyingKey(keyId).getEncoded(), equalTo(container.getVerifyingKey(keyId).getEncoded()));
  }

}
 
Example 18
Project: openjdk-jdk10   File: TestKeyFactory.java   View source code 6 votes vote down vote up
@Override
public void main(Provider p) throws Exception {
    if (p.getService("KeyFactory", "EC") == null) {
        System.out.println("Provider does not support EC, skipping");
        return;
    }
    int[] keyLengths = {192, 163, 409, 521};
    int len = 0;
    if (getNSSECC() == ECCState.Basic) {
        System.out.println("NSS Basic ECC only. Skipping 192, 163, & 409");
        len = 3;
    }
    KeyFactory kf = KeyFactory.getInstance("EC", p);
    for (; keyLengths.length > len ; len++) {
        System.out.println("Length "+keyLengths[len]);
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p);
        kpg.initialize(keyLengths[len]);
        KeyPair kp = kpg.generateKeyPair();
        test(kf, kp.getPrivate());
        test(kf, kp.getPublic());
    }
}
 
Example 19
Project: openjdk-jdk10   File: SolarisShortDSA.java   View source code 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 20
Project: OAuth-2.0-Cookbook   File: OAuth2AuthorizationServer.java   View source code 6 votes vote down vote up
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();

    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        keyGen.initialize(1024, random);

        KeyPair keyPair = keyGen.generateKeyPair();
        converter.setKeyPair(keyPair);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return converter;
}
 
Example 21
Project: xitk   File: KeyUtil.java   View source code 6 votes vote down vote up
private static KeyPairGenerator getKeyPairGenerator(String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    String alg = algorithm.toUpperCase();
    if ("ECDSA".equals(alg)) {
        alg = "EC";
    }
    synchronized (KEYPAIR_GENERATORS) {
        KeyPairGenerator kg = KEYPAIR_GENERATORS.get(algorithm);
        if (kg != null) {
            return kg;
        }

        kg = KeyPairGenerator.getInstance(algorithm, "BC");
        KEYPAIR_GENERATORS.put(algorithm, kg);
        return kg;
    }
}
 
Example 22
Project: DecompiledMinecraft   File: CryptManager.java   View source code 6 votes vote down vote up
/**
 * Generates RSA KeyPair
 */
public static KeyPair generateKeyPair()
{
    try
    {
        KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
        keypairgenerator.initialize(1024);
        return keypairgenerator.generateKeyPair();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        nosuchalgorithmexception.printStackTrace();
        LOGGER.error("Key pair generation failed!");
        return null;
    }
}
 
Example 23
Project: openjdk-jdk10   File: FinalizeHalf.java   View source code 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 24
Project: outcomes   File: Main.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        KeyPair kp = kpg.genKeyPair();

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
                RSAPrivateKeySpec.class);

        publicKey = fact.generatePublic(pub);
        privateKey = fact.generatePrivate(priv);

        String foo = rsaEncrypt("foo");

        byte[] decode = Base64.getDecoder().decode("foo");
        System.out.println(Base64.getEncoder().encodeToString(decode));

        System.out.println(rsaDecrypt(foo));

    }
 
Example 25
Project: react-native-caller-id-android   File: DataBase.java   View source code 6 votes vote down vote up
private static KeyPair createNewKeys(Context ctx, String alias) {
    KeyPair keyPair = null;
    try {
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 1);
        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx)
                .setAlias(alias)
                .setSubject(new X500Principal("CN=" + alias))
                .setSerialNumber(BigInteger.ONE)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", keyStoreInstance);
        generator.initialize(spec);
        keyPair = generator.generateKeyPair();
    } catch (Exception e) {
        Toast.makeText(ctx, "Exception " + e.getMessage() + " occured", Toast.LENGTH_LONG).show();
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return keyPair;
}
 
Example 26
Project: CacheManage   File: KeyStoreHelper.java   View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
static void createKeysM(String alias, boolean requireAuth) {
    try {
        KeyPairGenerator keyPairGenerator =
                KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA,
                        SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
        keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(alias,
                KeyProperties.PURPOSE_ENCRYPT
                        | KeyProperties.PURPOSE_DECRYPT).setAlgorithmParameterSpec(
                new RSAKeyGenParameterSpec(1024, F4))
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384,
                        KeyProperties.DIGEST_SHA512)
                // Only permit the private key to be used if the user authenticated
                // within the last five minutes.
                .setUserAuthenticationRequired(requireAuth)
                .build());
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
    } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }
}
 
Example 27
Project: springboot-training   File: RSACoder.java   View source code 6 votes vote down vote up
/**
 * 初始化密钥
 * 
 * @return
 * @throws Exception
 */
public static Map<String, Key> initKey() {
	try {
		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, Key> keyMap = new HashMap<String, Key>(2);

		keyMap.put(PUBLIC_KEY, publicKey);
		keyMap.put(PRIVATE_KEY, privateKey);
		return keyMap;
	} catch (NoSuchAlgorithmException e) {
		throw new RuntimeException("初始化密钥出错 " + e.getMessage());
	}
}
 
Example 28
Project: CustomWorldGen   File: CryptManager.java   View source code 6 votes vote down vote up
/**
 * Generates RSA KeyPair
 */
public static KeyPair generateKeyPair()
{
    try
    {
        KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
        keypairgenerator.initialize(1024);
        return keypairgenerator.generateKeyPair();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        nosuchalgorithmexception.printStackTrace();
        LOGGER.error("Key pair generation failed!");
        return null;
    }
}
 
Example 29
Project: DMS   File: RSA.java   View source code 6 votes vote down vote up
private static void init() {
	try {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher = Cipher.getInstance(INSTANCE_TYPE);
		KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
		generator.initialize(1024);
		KeyPair pair = generator.generateKeyPair();
		PUBLIC_KEY = org.apache.commons.codec.binary.Base64.encodeBase64String(pair.getPublic().getEncoded());
		privKey = pair.getPrivate();
	} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
		e.printStackTrace();
		Log.e(e.getMessage());
	}
}
 
Example 30
Project: azure-libraries-for-java   File: TestContainerService.java   View source code 6 votes vote down vote up
private String getSshKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair keyPair=keyPairGenerator.generateKeyPair();
    RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
    ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(byteOs);
    dos.writeInt("ssh-rsa".getBytes().length);
    dos.write("ssh-rsa".getBytes());
    dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
    dos.write(publicKey.getPublicExponent().toByteArray());
    dos.writeInt(publicKey.getModulus().toByteArray().length);
    dos.write(publicKey.getModulus().toByteArray());
    String publicKeyEncoded = new String(
            Base64.encodeBase64(byteOs.toByteArray()));
    return "ssh-rsa " + publicKeyEncoded + " ";
}
 
Example 31
Project: azure-libraries-for-java   File: TestKubernetesCluster.java   View source code 6 votes vote down vote up
private String getSshKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair keyPair=keyPairGenerator.generateKeyPair();
    RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
    ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(byteOs);
    dos.writeInt("ssh-rsa".getBytes().length);
    dos.write("ssh-rsa".getBytes());
    dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
    dos.write(publicKey.getPublicExponent().toByteArray());
    dos.writeInt(publicKey.getModulus().toByteArray().length);
    dos.write(publicKey.getModulus().toByteArray());
    String publicKeyEncoded = new String(
        Base64.encodeBase64(byteOs.toByteArray()));
    return "ssh-rsa " + publicKeyEncoded + " ";
}
 
Example 32
Project: BaseClient   File: CryptManager.java   View source code 6 votes vote down vote up
/**
 * Generates RSA KeyPair
 */
public static KeyPair generateKeyPair()
{
    try
    {
        KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
        keypairgenerator.initialize(1024);
        return keypairgenerator.generateKeyPair();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        nosuchalgorithmexception.printStackTrace();
        LOGGER.error("Key pair generation failed!");
        return null;
    }
}
 
Example 33
Project: wolfcrypt-jni   File: EccTest.java   View source code 6 votes vote down vote up
@Test
public void getEccCurveNameFromSpec()
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {

    /* generate key pair */
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec genSpec = new ECGenParameterSpec("secp256r1");
    kpg.initialize(genSpec);

    KeyPair pair = kpg.genKeyPair();
    ECPrivateKey priv = (ECPrivateKey)pair.getPrivate();

    ECParameterSpec spec = priv.getParams();

    String curveName = Ecc.getCurveName(spec);

    assertEquals(curveName, "SECP256R1");
}
 
Example 34
Project: NBANDROID-V2   File: ApkUtils.java   View source code 5 votes vote down vote up
private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(String asymmetric, String sign, int validityYears, String dn) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException {
    Preconditions.checkArgument(validityYears > 0, "validityYears <= 0");
    KeyPair keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair();
    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + validityYears * 31536000000l);
    X500Name issuer = new X500Name(new X500Principal(dn).getName());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo);
    ContentSigner signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider());
    X509Certificate certificate = converter.getCertificate(holder);
    return Pair.of(keyPair.getPrivate(), certificate);
}
 
Example 35
Project: holon-core   File: TestJwt.java   View source code 5 votes vote down vote up
@Test
public void testJWTAuthentication_signed_asymmetric() throws Exception {

	KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
	keyGen.initialize(512);
	KeyPair keyPair = keyGen.genKeyPair();
	PrivateKey privateKey = keyPair.getPrivate();
	PublicKey publicKey = keyPair.getPublic();

	final JwtConfiguration cfg = JwtConfiguration.builder().signatureAlgorithm(SignatureAlgorithm.RS256.getValue())
			.privateKey(privateKey).publicKey(publicKey).build();

	final Realm realm = Realm.builder().authenticator(JwtAuthenticator.builder().configuration(cfg).build())
			.build();

	Authentication authc = Authentication.builder("testuser").root(true).build();

	String jwt = JwtTokenBuilder.buildJWT(authc, "TestId", "TestUnit", 20000L, SignatureAlgorithm.RS256,
			privateKey);
	assertNotNull(jwt);

	Authentication authenticated = realm.authenticate(AuthenticationToken.bearer(jwt));
	assertNotNull(authenticated);
	assertEquals(authc, authenticated);
	assertEquals("TestUnit", authenticated.getParameter(Claims.ISSUER, String.class).get());
	assertEquals("TestId", authenticated.getParameter(Claims.ID, String.class).get());

}
 
Example 36
Project: openjdk-jdk10   File: TestDH2048.java   View source code 5 votes vote down vote up
private static void checkUnsupportedKeySize(KeyPairGenerator kpg, int ks)
    throws Exception {
    try {
        kpg.initialize(ks);
        throw new Exception("Expected IPE not thrown for " + ks);
    } catch (InvalidParameterException ipe) {
    }
}
 
Example 37
Project: firebase-admin-java   File: FirebaseTokenFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void failsWhenUidIsTooLong() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock);

  thrown.expect(IllegalStateException.class);
  tokenFactory.createSignedCustomAuthTokenForUser(
      Strings.repeat("a", 129), ISSUER, keys.getPrivate());
}
 
Example 38
Project: firebase-admin-java   File: FirebaseTokenFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void failsWhenExtraClaimsContainsReservedKey() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock);

  Map<String, Object> extraClaims = ImmutableMap.<String, Object>of("iss", "repeat issuer");
  thrown.expect(IllegalArgumentException.class);
  tokenFactory.createSignedCustomAuthTokenForUser(
      USER_ID, extraClaims, ISSUER, keys.getPrivate());
}
 
Example 39
Project: Myst   File: MPCTestClient.java   View source code 5 votes vote down vote up
private static ECPoint randECPoint() throws Exception {
    ECParameterSpec ecSpec_named = ECNamedCurveTable
            .getParameterSpec("secp256r1"); // NIST P-256
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA", "BC");
    kpg.initialize(ecSpec_named);
    KeyPair apair = kpg.generateKeyPair();
    ECPublicKey apub = (ECPublicKey) apair.getPublic();
    return apub.getQ();
}
 
Example 40
Project: xrd4j   File: CryptoHelperTest.java   View source code 5 votes vote down vote up
/**
 * Test signature with a SOAP message and generate ECDSA keys during the
 * test.
 */
public void testSignature4() {
    String data = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:id=\"http://x-road.eu/xsd/identifiers\" xmlns:xrd=\"http://x-road.eu/xsd/xroad.xsd\"><SOAP-ENV:Header><xrd:client id:objectType=\"SUBSYSTEM\"><id:xRoadInstance>FI</id:xRoadInstance><id:memberClass>GOV</id:memberClass><id:memberCode>MEMBER1</id:memberCode><id:subsystemCode>subsystem</id:subsystemCode></xrd:client><xrd:service id:objectType=\"SERVICE\"><id:xRoadInstance>FI</id:xRoadInstance><id:memberClass>COM</id:memberClass><id:memberCode>MEMBER2</id:memberCode><id:subsystemCode>subsystem</id:subsystemCode><id:serviceCode>getRandom</id:serviceCode><id:serviceVersion>v1</id:serviceVersion></xrd:service><xrd:userId>EE1234567890</xrd:userId><xrd:id>ID-1234567890</xrd:id><xrd:protocolVersion>4.0</xrd:protocolVersion><xrd:requestHash algorithmId=\"SHA-512\">ZPbWPAOcJxzE81EmSk//R3DUQtqwMcuMMF9tsccJypdNcukzICQtlhhr3a/bTmexDrn8e/BrBVyl2t0ni/cUvw==</xrd:requestHash></SOAP-ENV:Header><SOAP-ENV:Body><ns1:getRandomResponse xmlns:ns1=\"http://producer.x-road.ee\"><request><data>1234567890 Каллио</data></request><response><data>9876543210</data></response></ns1:getRandomResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
        keyGen.initialize(256, new SecureRandom());
        KeyPair keyPair = keyGen.generateKeyPair();
        String signature = CryptoHelper.createSignature(keyPair.getPrivate(), data, "SHA512withECDSA");
        assertEquals(true, CryptoHelper.verifySignature(keyPair.getPublic(), data, signature, "SHA512withECDSA"));
    } catch (Exception e) {
        fail(e.getMessage());
    }
}