Java 类java.security.KeyPairGenerator 实例源码

项目:PACE    文件:ValueSignerTest.java   
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)));
  }
}
项目:AppCoins-ethereumj    文件:ECKey.java   
/**
 * 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());
    }
}
项目:talchain    文件:ECKey.java   
/**
 * 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());
    }
}
项目:AppCoins-ethereumj    文件:ECKey.java   
/**
 * 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());
    }
}
项目:firebase-admin-java    文件:FirebaseTokenFactoryTest.java   
@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())));
}
项目:AppCoins-ethereumj    文件:ECKeyTest.java   
@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");
}
项目:GitHub    文件:GeneratePubkeyActivity.java   
@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);
    }
}
项目:bouncr    文件:JsonWebTokenTest.java   
@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);
}
项目:openjdk-jdk10    文件:SupportedDHKeys.java   
@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);
    }
}
项目:jdk8u-jdk    文件:GenerateKeypair.java   
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");
        }
    }
项目:sensorhub-cloud-iot    文件:MqttAuthentication.java   
/**
 * 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();
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@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);
    }
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@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) {}
    }
}
项目:spring-web-jsflow    文件:GeneratedKeyPairFactory.java   
@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();
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@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();
    }
}
项目:L2J-Global    文件:GameServerTable.java   
/**
 * 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!");
    }
}
项目:PACE    文件:LocalSignatureKeyContainerTest.java   
@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()));
  }

}
项目:openjdk-jdk10    文件:TestKeyFactory.java   
@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());
    }
}
项目:openjdk-jdk10    文件:SolarisShortDSA.java   
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;
        }
    }
}
项目:OAuth-2.0-Cookbook    文件:OAuth2AuthorizationServer.java   
@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;
}
项目:xitk    文件:KeyUtil.java   
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;
    }
}
项目:DecompiledMinecraft    文件:CryptManager.java   
/**
 * 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;
    }
}
项目:openjdk-jdk10    文件:FinalizeHalf.java   
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++;
    }
}
项目:outcomes    文件:Main.java   
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));

    }
项目:react-native-caller-id-android    文件:DataBase.java   
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;
}
项目:CacheManage    文件:KeyStoreHelper.java   
@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);
    }
}
项目:springboot-training    文件:RSACoder.java   
/**
 * 初始化密钥
 * 
 * @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());
    }
}
项目:CustomWorldGen    文件:CryptManager.java   
/**
 * 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;
    }
}
项目:DMS    文件:RSA.java   
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());
    }
}
项目:azure-libraries-for-java    文件:TestContainerService.java   
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 + " ";
}
项目:azure-libraries-for-java    文件:TestKubernetesCluster.java   
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 + " ";
}
项目:BaseClient    文件:CryptManager.java   
/**
 * 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;
    }
}
项目:wolfcrypt-jni    文件:EccTest.java   
@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");
}
项目:NBANDROID-V2    文件:ApkUtils.java   
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);
}
项目:holon-core    文件:TestJwt.java   
@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());

}
项目:openjdk-jdk10    文件:TestDH2048.java   
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) {
    }
}
项目:firebase-admin-java    文件:FirebaseTokenFactoryTest.java   
@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());
}
项目:firebase-admin-java    文件:FirebaseTokenFactoryTest.java   
@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());
}
项目:Myst    文件:MPCTestClient.java   
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();
}
项目:xrd4j    文件:CryptoHelperTest.java   
/**
 * 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());
    }
}