Java Code Examples for java.security.KeyPairGenerator

The following examples show how to use java.security.KeyPairGenerator. These examples are extracted from open source projects. 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 Project: connector-sdk   Source File: SensitiveDataCodecTest.java    License: 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 2
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 3
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 4
@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 5
Source Project: DataLink   Source File: SecretUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初始化密钥 for RSA ALGORITHM
 *
 * @return
 * @throws Exception
 */
public static String[] initKey() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator
            .getInstance(KEY_ALGORITHM_RSA);
    keyPairGen.initialize(1024);

    KeyPair keyPair = keyPairGen.generateKeyPair();

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

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

    String[] publicAndPrivateKey = {
            encryptBASE64(publicKey.getEncoded()),
            encryptBASE64(privateKey.getEncoded())};

    return publicAndPrivateKey;
}
 
Example 6
Source Project: Auditor   Source File: AttestationProtocol.java    License: 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 7
Source Project: gsc-core   Source File: ECKey.java    License: 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 8
Source Project: RairDemo   Source File: RSAUtil.java    License: 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 9
Source Project: jdk8u60   Source File: GenerateKeypair.java    License: 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 10
Source Project: protect   Source File: EciesEncryptionTest.java    License: 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 11
@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 12
Source Project: mcg-helper   Source File: RSAEncrypt.java    License: 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 13
/**
 * 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 14
Source Project: javasdk   Source File: ECKey.java    License: 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 15
Source Project: openjsse   Source File: DHKeyExchange.java    License: 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 16
Source Project: openjsse   Source File: DHKeyExchange.java    License: 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 17
Source Project: openjsse   Source File: ECDHKeyExchange.java    License: 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 18
Source Project: WeEvent   Source File: WeEventFileClient.java    License: 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 19
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
Source Project: openjdk-jdk8u   Source File: SpecTest.java    License: 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 21
Source Project: aion   Source File: ECKeySecp256k1.java    License: 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 22
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 23
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 24
Source Project: tron-wallet-android   Source File: ECKey.java    License: 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 25
Source Project: openjdk-jdk8u   Source File: FinalizeHalf.java    License: 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 26
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 27
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 28
Source Project: java-11-examples   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate one-time server keypair.
 * @return
 */
public static Iterable<KeyPair> generateKeyPairs() {
    try {
        List<KeyPair> result = new ArrayList<>();
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keyPair = keyGen.genKeyPair();
        result.add(keyPair);
        return Collections.unmodifiableCollection(result);
    } catch (NoSuchAlgorithmException e) {
        return Collections.emptyList();
    }
}
 
Example 29
Source Project: samples-android   Source File: EncryptionManagerAPI18.java    License: Apache License 2.0 5 votes vote down vote up
@Override
boolean generateKeyPair(Context context, KeyPairGenerator generator, String keyAlias,
                        int keySize, String encryptionPadding, String blockMode,
                        boolean isStrongBoxBacked, @Nullable byte[] seed) {
    Calendar startDate = Calendar.getInstance();
    //probable fix for the timezone issue
    startDate.add(Calendar.HOUR_OF_DAY, RSA_CALENDAR_HOURS_OFFSET);
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.YEAR, RSA_CALENDAR_MAX_YEARS);

    try {
        KeyPairGeneratorSpec.Builder builder = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(keyAlias)
                .setSerialNumber(BigInteger.ONE)
                .setSubject(new X500Principal(
                        "CN = Secured Preference Store, O = Devliving Online"))
                .setStartDate(startDate.getTime())
                .setEndDate(endDate.getTime());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            builder.setKeySize(keySize);
        }
        if (seed != null && seed.length > 0) {
            SecureRandom random = new SecureRandom(seed);
            generator.initialize(builder.build(), random);
        } else {
            generator.initialize(builder.build());
        }

        return true;
    } catch (InvalidAlgorithmParameterException e) {
        Log.e(TAG, "initialize KeyPairGenerator: ", e);
    }
    return false;
}
 
Example 30
Source Project: smallrye-jwt   Source File: JwtEncryptTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEncryptWithInvalidRSAKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    PublicKey key = keyPairGenerator.generateKeyPair().getPublic();
    try {
        Jwt.claims().jwe().encrypt(key);
        Assert.fail("JwtEncryptionException is expected due to the invalid key size");
    } catch (JwtEncryptionException ex) {
        Assert.assertEquals("SRJWT05001: A key of size 2048 bits or larger MUST be used with the 'RSA-OAEP-256' algorithm",
                ex.getMessage());
    }
}