java.security.KeyPairGenerator#genKeyPair ( )源码实例Demo

下面列出了java.security.KeyPairGenerator#genKeyPair ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: dragonwell8_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");
        }
    }
 
源代码2 项目: quarkus   文件: JCATestCase.java
@Test
public void testVerifyRSASig() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(4096);
    KeyPair keyPair = keyPairGenerator.genKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    byte[] encoded = publicKey.getEncoded();
    byte[] pemEncoded = Base64.getEncoder().encode(encoded);
    String pemString = new String(pemEncoded, "UTF-8");

    RestAssured.given()
            .queryParam("msg", "Hello verifyRSASig")
            .queryParam("publicKey", pemString)
            .queryParam("sig", "")
            .when()
            .get("/jca/verifyRSASig")
            .then()
            .statusCode(200)
            .body(is("true"));
}
 
源代码3 项目: TencentKona-8   文件: TestCipherKeyWrapperTest.java
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);
    }
}
 
源代码4 项目: quarkus   文件: JCATestCase.java
@Test
public void testDecodeRSAKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(4096);
    KeyPair keyPair = keyPairGenerator.genKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    byte[] encoded = publicKey.getEncoded();
    byte[] pemEncoded = Base64.getEncoder().encode(encoded);
    String pemString = new String(pemEncoded, "UTF-8");

    RestAssured.given()
            .queryParam("pemEncoded", pemString)
            .when()
            .get("/jca/decodeRSAKey")
            .then()
            .statusCode(200)
            .body(is("RSA"));
}
 
源代码5 项目: SoloPi   文件: AdbCrypto.java
/**
 * Creates a new AdbCrypto object by generating a new key pair.
 * @param base64 Implementation of base 64 conversion interface required by ADB 
 * @return A new AdbCrypto object
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 */
public static AdbCrypto generateAdbKeyPair(AdbBase64 base64) throws NoSuchAlgorithmException
{
	AdbCrypto crypto = new AdbCrypto();

	KeyPairGenerator rsaKeyPg = KeyPairGenerator.getInstance("RSA");
	rsaKeyPg.initialize(KEY_LENGTH_BITS);
	
	crypto.keyPair = rsaKeyPg.genKeyPair();
	crypto.base64 = base64;
	
	return crypto;
}
 
源代码6 项目: java-11-examples   文件: Utils.java
/**
 * 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();
    }
}
 
@Override
public WorkerKeyPair generate() {
  KeyPairGenerator kpg = null;
  try {
    kpg = KeyPairGenerator.getInstance(ALGORITHM);
  } catch (NoSuchAlgorithmException e) {
    monitor.severe(() -> "NoSuchAlgorithmException for: " + ALGORITHM, e);
    throw new RuntimeException("NoSuchAlgorithmException generating key", e);
  }
  kpg.initialize(1024);
  KeyPair keyPair = kpg.genKeyPair();
  return new WorkerKeyPair() {
    @Override
    public String getInstanceId() {
      return UUID.randomUUID().toString();
    }

    @Override
    public byte[] getEncodedPublicKey() {
      return keyPair.getPublic().getEncoded();
    }

    @Override
    public byte[] getEncodedPrivateKey() {
      return keyPair.getPrivate().getEncoded();
    }
  };
}
 
源代码8 项目: L2jOrg   文件: GameServerManager.java
private void loadRSAKeys() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4);
    keyGen.initialize(spec);

    _keyPairs = new KeyPair[KEYS_SIZE];
    for (int i = 0; i < KEYS_SIZE; i++) {
        _keyPairs[i] = keyGen.genKeyPair();
    }
    LOGGER.info("Cached {} RSA keys for Game Server communication.", _keyPairs.length);
}
 
源代码9 项目: TVRemoteIME   文件: AdbCrypto.java
/**
 * Creates a new AdbCrypto object by generating a new key pair.
 * @param base64 Implementation of base 64 conversion interface required by ADB 
 * @return A new AdbCrypto object
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 */
public static AdbCrypto generateAdbKeyPair(AdbBase64 base64) throws NoSuchAlgorithmException
{
	AdbCrypto crypto = new AdbCrypto();

	KeyPairGenerator rsaKeyPg = KeyPairGenerator.getInstance("RSA");
	rsaKeyPg.initialize(KEY_LENGTH_BITS);
	
	crypto.keyPair = rsaKeyPg.genKeyPair();
	crypto.base64 = base64;
	
	return crypto;
}
 
源代码10 项目: data-transfer-project   文件: JWEKeyGenerator.java
@Override
public WorkerKeyPair generate() {
  monitor.debug(() -> "JWEKeyGenerator generate");
  KeyPairGenerator kpg = null;
  try {
    kpg = KeyPairGenerator.getInstance(ALGORITHM);
  } catch (NoSuchAlgorithmException e) {
    monitor.severe(() -> "NoSuchAlgorithmException for: " + ALGORITHM, e);
    throw new RuntimeException("NoSuchAlgorithmException generating key", e);
  }
  kpg.initialize(1024);
  KeyPair keyPair = kpg.genKeyPair();
  monitor.debug(() -> "JWEKeyGenerator generated WorkerKeyPair");
  return new WorkerKeyPair() {
    @Override
    public String getInstanceId() {
      return UUID.randomUUID().toString();
    }

    @Override
    public byte[] getEncodedPublicKey() {
      return keyPair.getPublic().getEncoded();
    }

    @Override
    public byte[] getEncodedPrivateKey() {
      return keyPair.getPrivate().getEncoded();
    }
  };
}
 
源代码11 项目: wind-im   文件: RSACrypto.java
public static KeyPair buildRSAKeyPair() throws NoSuchAlgorithmException {
	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
	keyPairGenerator.initialize(1024);
	return keyPairGenerator.genKeyPair();
}
 
源代码12 项目: dragonwell8_jdk   文件: Copy.java
public static void main(String args[]) throws Exception {
    KeyPairGenerator kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    KeyPair kp = kg.genKeyPair();

    Signature signature = Signature.getInstance(DSA);
    Test original = new Test();
    SignedObject so = new SignedObject(original, kp.getPrivate(),
            signature);
    System.out.println("Signature algorithm: " + so.getAlgorithm());

    signature = Signature.getInstance(DSA, "SUN");
    if (!so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Verification failed");
    }

    kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    kp = kg.genKeyPair();

    if (so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Unexpected success");
    }

    Object copy = so.getObject();
    if (!original.equals(copy)) {
        throw new RuntimeException("Signed object is not equal "
                + "to original one: " + copy);
    }

    /*
     * The signed object is a copy of an original one.
     * Once the copy is made, further manipulation
     * of the original object shouldn't has any effect on the copy.
     */
    original.set(MAGIC - 1);
    copy = so.getObject();
    if (original.equals(copy)) {
        throw new RuntimeException("Signed object is not a copy "
                + "of original one: " + copy);
    }

    System.out.println("Test passed");
}
 
源代码13 项目: dragonwell8_jdk   文件: XMLDSigWithSecMgr.java
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

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

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    System.setProperty("java.security.policy",
            System.getProperty("test.src", ".") + File.separator + "policy");
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
源代码14 项目: openjdk-jdk8u   文件: Copy.java
public static void main(String args[]) throws Exception {
    KeyPairGenerator kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    KeyPair kp = kg.genKeyPair();

    Signature signature = Signature.getInstance(DSA);
    Test original = new Test();
    SignedObject so = new SignedObject(original, kp.getPrivate(),
            signature);
    System.out.println("Signature algorithm: " + so.getAlgorithm());

    signature = Signature.getInstance(DSA, "SUN");
    if (!so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Verification failed");
    }

    kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    kp = kg.genKeyPair();

    if (so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Unexpected success");
    }

    Object copy = so.getObject();
    if (!original.equals(copy)) {
        throw new RuntimeException("Signed object is not equal "
                + "to original one: " + copy);
    }

    /*
     * The signed object is a copy of an original one.
     * Once the copy is made, further manipulation
     * of the original object shouldn't has any effect on the copy.
     */
    original.set(MAGIC - 1);
    copy = so.getObject();
    if (original.equals(copy)) {
        throw new RuntimeException("Signed object is not a copy "
                + "of original one: " + copy);
    }

    System.out.println("Test passed");
}
 
private KeyPair RSAKeyPair() throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    return kpg.genKeyPair();
}
 
源代码16 项目: openzaly   文件: RSACrypto.java
public static KeyPair buildRSAKeyPair() throws NoSuchAlgorithmException {
	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
	keyPairGenerator.initialize(1024);
	return keyPairGenerator.genKeyPair();
}
 
源代码17 项目: smallrye-jwt   文件: KeyUtils.java
public static KeyPair generateKeyPair(int keySize, SignatureAlgorithm algo) throws NoSuchAlgorithmException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyFactoryAlgorithm(algo));
    keyPairGenerator.initialize(keySize);
    return keyPairGenerator.genKeyPair();
}
 
源代码18 项目: openzaly   文件: RSACrypto.java
public static KeyPair buildRSAKeyPair() throws NoSuchAlgorithmException {
	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
	keyPairGenerator.initialize(1024);
	return keyPairGenerator.genKeyPair();
}
 
/**
 * Generate a new RSA keypair.
 *
 * @param keySize - the size of the key
 * @return KeyPair
 * @throws NoSuchAlgorithmException on failure to load RSA key generator
 */
public static KeyPair generateKeyPair(final int keySize) throws NoSuchAlgorithmException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keySize);
    return keyPairGenerator.genKeyPair();
}
 
源代码20 项目: quarkus-quickstarts   文件: TokenUtils.java
/**
 * Generate a new RSA keypair.
 *
 * @param keySize - the size of the key
 * @return KeyPair
 * @throws NoSuchAlgorithmException on failure to load RSA key generator
 */
public static KeyPair generateKeyPair(final int keySize) throws NoSuchAlgorithmException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keySize);
    return keyPairGenerator.genKeyPair();
}