當前位置: 首頁>>代碼示例>>Java>>正文


Java KeyPairGenerator類代碼示例

本文整理匯總了Java中java.security.KeyPairGenerator的典型用法代碼示例。如果您正苦於以下問題:Java KeyPairGenerator類的具體用法?Java KeyPairGenerator怎麽用?Java KeyPairGenerator使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


KeyPairGenerator類屬於java.security包,在下文中一共展示了KeyPairGenerator類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: signatureTest

import java.security.KeyPairGenerator; //導入依賴的package包/類
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)));
  }
}
 
開發者ID:mit-ll,項目名稱:PACE,代碼行數:26,代碼來源:ValueSignerTest.java

示例2: ECKey

import java.security.KeyPairGenerator; //導入依賴的package包/類
/**
 * 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());
    }
}
 
開發者ID:Aptoide,項目名稱:AppCoins-ethereumj,代碼行數:25,代碼來源:ECKey.java

示例3: ECKey

import java.security.KeyPairGenerator; //導入依賴的package包/類
/**
 * 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());
    }
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:25,代碼來源:ECKey.java

示例4: checkSignatureForToken

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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())));
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:24,代碼來源:FirebaseTokenFactoryTest.java

示例5: testInvalidPrivateKey

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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");
}
 
開發者ID:Aptoide,項目名稱:AppCoins-ethereumj,代碼行數:9,代碼來源:ECKeyTest.java

示例6: run

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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);
	}
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:19,代碼來源:GeneratePubkeyActivity.java

示例7: test

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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);
}
 
開發者ID:kawasima,項目名稱:bouncr,代碼行數:26,代碼來源:JsonWebTokenTest.java

示例8: main

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:24,代碼來源:SupportedDHKeys.java

示例9: main

import java.security.KeyPairGenerator; //導入依賴的package包/類
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");
        }
    }
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:18,代碼來源:GenerateKeypair.java

示例10: generateAuthenticationKey

import java.security.KeyPairGenerator; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:androidthings,項目名稱:sensorhub-cloud-iot,代碼行數:21,代碼來源:MqttAuthentication.java

示例11: testKeyPairGeneratorEccMultipleInits

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:wolfSSL,項目名稱:wolfcrypt-jni,代碼行數:18,代碼來源:WolfCryptKeyPairGeneratorTest.java

示例12: testKeyPairGeneratorEccInitializeWithKeySize

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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) {}
    }
}
 
開發者ID:wolfSSL,項目名稱:wolfcrypt-jni,代碼行數:20,代碼來源:WolfCryptKeyPairGeneratorTest.java

示例13: createInstance

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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();
}
 
開發者ID:szegedi,項目名稱:spring-web-jsflow,代碼行數:18,代碼來源:GeneratedKeyPairFactory.java

示例14: testKeyPairGeneratorEccKeyGenAllCurves

import java.security.KeyPairGenerator; //導入依賴的package包/類
@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();
    }
}
 
開發者ID:wolfSSL,項目名稱:wolfcrypt-jni,代碼行數:19,代碼來源:WolfCryptKeyPairGeneratorTest.java

示例15: main

import java.security.KeyPairGenerator; //導入依賴的package包/類
public static void main(String[] args) throws Exception {

		TestJCAProvider d = new TestJCAProvider();
		// Add dynamically the desired provider
		Security.addProvider(new PaillierProvider());
		
		/////////////////////////////////////////////////////////////////////
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("Paillier");
		kpg.initialize(32);
		KeyPair keyPair = kpg.generateKeyPair();
		PublicKey pubKey = keyPair.getPublic();
		PrivateKey privKey = keyPair.getPrivate();
		final Cipher cipher = Cipher.getInstance("Paillier");
		final Cipher cipherHP = Cipher.getInstance("PaillierHP");
		System.out.println("The Paillier public key through Generator is \n"+keyPair.toString());
		System.out.println("The Paillier public key is \n"+keyPair.getPublic().toString());
		System.out.println("The Paillier private key is \n"+keyPair.getPrivate().toString());
		String plainText = "101";
		String plaintext1 = "101";
		// get the n
		String delims = "[,]";
		String[] keyComponents = pubKey.toString().split(delims);
		String keyComponent = "";
		for (String keyComponent2 : keyComponents) {
			if (keyComponent2.startsWith("n")) {
				keyComponent = keyComponent2.substring(2);// ignoring 'n:' or 'r:'
			}
		}
		BigInteger n = new BigInteger(keyComponent);
		BigInteger first = new BigInteger(plainText);
		BigInteger second = new BigInteger(plaintext1);
		BigInteger n2 = n.multiply(n);

		// encrypt
		BigInteger codedBytes = d.encrypt(first.toByteArray(), pubKey,cipherHP);
		BigInteger codedBytes12 = d.encrypt(second.toByteArray(), pubKey,cipherHP);
		//product
		BigInteger product = codedBytes.multiply(codedBytes12);

		// product mod n^2
		BigInteger tallyProduct = product.mod(n2);
	    System.out.println(" Product mod n^2:      "+tallyProduct);
	    d.decrypt(tallyProduct.toByteArray(), privKey,cipherHP);

		d.decrypt(codedBytes.toByteArray(),privKey,cipherHP);
		d.decrypt(codedBytes12.toByteArray(),privKey,cipherHP);
		
		//////////////////////////////BLOCK EXAMPLE/////////////////////////////////
		String plainTextBlock = "This Provider working correctly and its safe 10000000000000000011000000000000000001";
		System.out.println("This is the message which will be encrypted: " + plainTextBlock);
		
		// encrypt
		byte[] codedBytesBlock = d.encryptBlock(plainTextBlock.getBytes(), pubKey,cipher);
		String codedMessageBlock = new String(codedBytesBlock);
		String codedMessageBlockInHEX = formatingHexRepresentation(codedBytesBlock);
		System.out.println("\n" + "ENCRYPTED :  \n" + codedMessageBlock);
		System.out.println("\n" + "ENCRYPTED in HEX:  \n" + codedMessageBlockInHEX);

		// decrypt
		byte[] encodedBytesBlock = d.decryptBlock(codedMessageBlock, privKey,cipher);
		String encodedMessageBlock = new String(encodedBytesBlock);
		System.out.println("\n" + "DECRYPTED:  \n" + encodedMessageBlock);
			
		}
 
開發者ID:peterstefanov,項目名稱:paillier,代碼行數:65,代碼來源:TestJCAProvider.java


注:本文中的java.security.KeyPairGenerator類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。