java.security.KeyPair Java Examples

The following examples show how to use java.security.KeyPair. 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 File: SecureTestUtils.java    From kareldb with Apache License 2.0 7 votes vote down vote up
public static void createKeyStore(
    File keyStoreFile,
    String keyStorePassword,
    List<X509Certificate> clientCerts,
    List<KeyPair> keyPairs
) throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);

    for (int i = 0; i < clientCerts.size(); i++) {
        keyStore.setKeyEntry(
            "client-" + i,
            keyPairs.get(i).getPrivate(),
            keyStorePassword.toCharArray(),
            new Certificate[]{clientCerts.get(i)}
        );
    }

    FileOutputStream out = new FileOutputStream(keyStoreFile);
    keyStore.store(out, keyStorePassword.toCharArray());
    out.close();

}
 
Example #2
Source File: Encryption.java    From Wurst7 with GNU General Public License v3.0 7 votes vote down vote up
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
	throws GeneralSecurityException, ReflectiveOperationException,
	IOException
{
	KeyFactory factory = KeyFactory.getInstance("RSA");
	
	// load public key
	PublicKey publicKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(publicFile)))
	{
		publicKey = factory.generatePublic(new RSAPublicKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	// load private key
	PrivateKey privateKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(privateFile)))
	{
		privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	return new KeyPair(publicKey, privateKey);
}
 
Example #3
Source File: SignatureExample.java    From CompetitiveJava with MIT License 7 votes vote down vote up
public static void writeKeyToFile(String folderPath, KeyPair keyPair) throws IOException {
	File publicKeyFile = new File(folderPath.concat("/publicKey.pem"));
	publicKeyFile.getParentFile().mkdirs();
	
	File privateKeyFile = new File(folderPath.concat("/privateKey.pem"));
	privateKeyFile.getParentFile().mkdir();

	PrintWriter publicKeyOut = new PrintWriter(publicKeyFile);
	publicKeyOut.write("-----BEGIN PUBLIC KEY-----");
	publicKeyOut.write(System.lineSeparator());
	publicKeyOut.write(Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded()));
	publicKeyOut.write(System.lineSeparator());
	publicKeyOut.write("-----END PUBLIC KEY-----");
	publicKeyOut.close();
	
	PrintWriter privateKeyOut = new PrintWriter(privateKeyFile);
	privateKeyOut.write("-----BEGIN PRIVATE KEY-----");
	privateKeyOut.write(System.lineSeparator());
	privateKeyOut.write(Base64.getMimeEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
	privateKeyOut.write(System.lineSeparator());
	privateKeyOut.write("-----END PRIVATE KEY-----");
	privateKeyOut.close();
}
 
Example #4
Source File: AsymmetricKeyEncryptionClientDemo.java    From markdown-image-kit with MIT License 6 votes vote down vote up
private static void buildAndSaveAsymKeyPair() throws IOException, NoSuchAlgorithmException {
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(1024, srand);
    KeyPair keyPair = keyGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream fos = new FileOutputStream(pubKeyPath);
    fos.write(x509EncodedKeySpec.getEncoded());
    fos.close();

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    fos = new FileOutputStream(priKeyPath);
    fos.write(pkcs8EncodedKeySpec.getEncoded());
    fos.close();
}
 
Example #5
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceAccountToJwt() throws Exception {
  KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
  @SuppressWarnings("deprecation")
  ServiceAccountCredentials credentials = new ServiceAccountCredentials(
      null, "[email protected]", pair.getPrivate(), null, null) {
    @Override
    public AccessToken refreshAccessToken() {
      throw new AssertionError();
    }
  };

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);
  assertEquals(0, runPendingRunnables());

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  String[] authorization = Iterables.toArray(headers.getAll(AUTHORIZATION), String.class);
  assertEquals(1, authorization.length);
  assertTrue(authorization[0], authorization[0].startsWith("Bearer "));
  // JWT is reasonably long. Normal tokens aren't.
  assertTrue(authorization[0], authorization[0].length() > 300);
}
 
Example #7
Source File: ECDHKeyExchange.java    From openjsse with 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 #8
Source File: CredentialSafe.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #9
Source File: HTTPJwtAuthenticatorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testRS256() throws Exception {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    String jwsToken = Jwts.builder().setSubject("Leonard McCoy").signWith(SignatureAlgorithm.RS256, priv).compact();
    Settings settings = Settings.builder().put("signing_key", "-----BEGIN PUBLIC KEY-----\n"+BaseEncoding.base64().encode(pub.getEncoded())+"-----END PUBLIC KEY-----").build();

    HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null);
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", "Bearer "+jwsToken);

    AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null);
    Assert.assertNotNull(creds);
    Assert.assertEquals("Leonard McCoy", creds.getUsername());
    Assert.assertEquals(0, creds.getBackendRoles().size());
}
 
Example #10
Source File: TestCipherKeyWrapperTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #11
Source File: DHKeyExchange.java    From openjsse with 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 #12
Source File: RootCertificateGenerator.java    From CapturePacket with MIT License 6 votes vote down vote up
/**
 * Generates a new CA root certificate and private key.
 *
 * @return new root certificate and private key
 */
private CertificateAndKey generateRootCertificate() {
    long generationStart = System.currentTimeMillis();

    // create the public and private key pair that will be used to sign the generated certificate
    KeyPair caKeyPair = keyGenerator.generate();

    // delegate the creation and signing of the X.509 certificate to the certificate tool
    CertificateAndKey certificateAndKey = securityProviderTool.createCARootCertificate(
            rootCertificateInfo,
            caKeyPair,
            messageDigest);

    long generationFinished = System.currentTimeMillis();

    log.info("Generated CA root certificate and private key in {}ms. Key generator: {}. Signature algorithm: {}.",
            generationFinished - generationStart, keyGenerator, messageDigest);

    return certificateAndKey;
}
 
Example #13
Source File: SignatureTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String testAlg = args[0];
    int testSize = Integer.parseInt(args[1]);

    byte[] data = new byte[100];
    RandomFactory.getRandom().nextBytes(data);

    // create a key pair
    KeyPair kpair = generateKeys(KEYALG, testSize);
    Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
    Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
    // For signature algorithm, create and verify a signature

    Arrays.stream(privs).forEach(priv
            -> Arrays.stream(pubs).forEach(pub -> {
                try {
                    checkSignature(data, (PublicKey) pub, (PrivateKey) priv,
                            testAlg);
                } catch (NoSuchAlgorithmException | InvalidKeyException
                        | SignatureException | NoSuchProviderException ex) {
                    throw new RuntimeException(ex);
                }
            }
            ));

}
 
Example #14
Source File: ECKey.java    From javasdk with 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 File: FinalizeHalf.java    From dragonwell8_jdk with 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 #16
Source File: GenerateKeysExample.java    From jlibra with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Ed25519", "BC");
    KeyPair keyPair = kpGen.generateKeyPair();

    BCEdDSAPrivateKey privateKey = (BCEdDSAPrivateKey) keyPair.getPrivate();

    BCEdDSAPublicKey publicKey = (BCEdDSAPublicKey) keyPair.getPublic();

    AuthenticationKey authenticationKey = AuthenticationKey.fromPublicKey(publicKey);
    logger.info("Libra address: {}",
            AccountAddress.fromAuthenticationKey(authenticationKey));
    logger.info("Authentication key: {}", authenticationKey);
    logger.info("Public key: {}", ByteArray.from(publicKey.getEncoded()));
    logger.info("Private key: {}", ByteArray.from(privateKey.getEncoded()));
}
 
Example #17
Source File: RSAUtils.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 随机生成密钥对
 */
public static void genKeyPair() throws NoSuchAlgorithmException {
    // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    // 初始化密钥对生成器
    keyPairGen.initialize(KEY_SIZE, new SecureRandom());
    // 生成一个密钥对,保存在keyPair中
    KeyPair keyPair = keyPairGen.generateKeyPair();
    // 得到私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    // 得到公钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
    // 得到私钥字符串
    String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
    // 将公钥和私钥保存到Map
    keyMap.put(PUBLIC_KEY, publicKeyString);
    keyMap.put(PRIVATE_KEY, privateKeyString);
}
 
Example #18
Source File: RSAKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SSLPossession createPossession(HandshakeContext context) {
    try {
        EphemeralKeyManager ekm =
                context.sslContext.getEphemeralKeyManager();
        KeyPair kp = ekm.getRSAKeyPair(
                true, context.sslContext.getSecureRandom());
        if (kp != null) {
            return new EphemeralRSAPossession(
                    kp.getPrivate(), (RSAPublicKey)kp.getPublic());
        } else {
            // Could not generate the ephemeral key, ignore.
            return null;
        }
    } catch (RuntimeException rte) {
        // Could not determine keylength, ignore.
        return null;
    }
}
 
Example #19
Source File: KeyPairUtils.java    From WeBASE-Sign with Apache License 2.0 6 votes vote down vote up
/**
 * get ec key pair from guomi key pair data
 * @param keyPairData common key pair
 * @return ECKeyPair
 */
private ECKeyPair genEcPairFromKeyPair(KeyPair keyPairData) {
    try {
        SM2PrivateKey vk = (SM2PrivateKey) keyPairData.getPrivate();
        SM2PublicKey pk = (SM2PublicKey) keyPairData.getPublic();
        final byte[] publicKey = pk.getEncoded();
        final byte[] privateKey = vk.getEncoded();

        BigInteger biPublic = new BigInteger(Hex.toHexString(publicKey), 16);
        BigInteger biPrivate = new BigInteger(Hex.toHexString(privateKey), 16);

        ECKeyPair keyPair = new ECKeyPair(biPrivate, biPublic);
        return keyPair;
    } catch (Exception e) {
        log.error("KeyPairUtils create ec_keypair of guomi failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #20
Source File: TestDefaultCertificateClient.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testStoreCertificate() throws Exception {
  KeyPair keyPair = keyGenerator.generateKey();
  X509Certificate cert1 = generateX509Cert(keyPair);
  X509Certificate cert2 = generateX509Cert(keyPair);
  X509Certificate cert3 = generateX509Cert(keyPair);

  dnCertClient.storeCertificate(getPEMEncodedString(cert1), true);
  dnCertClient.storeCertificate(getPEMEncodedString(cert2), true);
  dnCertClient.storeCertificate(getPEMEncodedString(cert3), true);

  assertNotNull(dnCertClient.getCertificate(cert1.getSerialNumber()
      .toString()));
  assertNotNull(dnCertClient.getCertificate(cert2.getSerialNumber()
      .toString()));
  assertNotNull(dnCertClient.getCertificate(cert3.getSerialNumber()
      .toString()));
}
 
Example #21
Source File: FinalizeHalf.java    From TencentKona-8 with 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 #22
Source File: SolarisShortDSA.java    From TencentKona-8 with GNU General Public License v2.0 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 #23
Source File: OrionKeyUtils.java    From besu with Apache License 2.0 5 votes vote down vote up
public static KeyPair generateKeys() throws NoSuchAlgorithmException {
  final KeyPair keyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
  final PublicKey pubKey = keyPair.getPublic();
  final PrivateKey privKey = keyPair.getPrivate();

  LOG.debug("pubkey      : " + pubKey);
  LOG.debug("pubkey bytes: " + Bytes.wrap(pubKey.getEncoded()).toHexString());
  LOG.debug("pubkey b64  : " + Base64.getEncoder().encodeToString(pubKey.getEncoded()));

  LOG.debug("privkey      : " + privKey);
  LOG.debug("privkey bytes: " + Bytes.wrap(privKey.getEncoded()).toHexString());
  LOG.debug("privkey b64  : " + Base64.getEncoder().encodeToString(privKey.getEncoded()));

  return keyPair;
}
 
Example #24
Source File: Utils.java    From iroha-java with Apache License 2.0 5 votes vote down vote up
static <T extends Hashable> Primitive.Signature sign(T t, KeyPair kp) {
  byte[] rawSignature = new Ed25519Sha3().rawSign(t.hash(), kp);

  return Signature.newBuilder()
      .setSignature(
          Utils.toHex(rawSignature)
      )
      .setPublicKey(
          Utils.toHex(kp.getPublic().getEncoded())
      )
      .build();
}
 
Example #25
Source File: Correctness.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String SIGALG = "SHA1withRSA";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();

        SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
                Signature.getInstance(SIGALG));

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(so1);
        out.close();

        byte[] data = byteOut.toByteArray();

        SignedObject so2 = (SignedObject)new ObjectInputStream(
                new ByteArrayInputStream(data)).readObject();

        if (!so2.getObject().equals("Hello")) {
            throw new Exception("Content changed");
        }
        if (!so2.getAlgorithm().equals(SIGALG)) {
            throw new Exception("Signature algorithm unknown");
        }
        if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
            throw new Exception("Not verified");
        }
    }
 
Example #26
Source File: KeyPairUtils.java    From WeBASE-Sign with Apache License 2.0 5 votes vote down vote up
/**
 * create guomi keypair from privateKey
 * @param privateKey string
 * @return ECKeyPair guomi
 */
private ECKeyPair createGuomiKeyPair(String privateKey) {
    SM2KeyGenerator generator = new SM2KeyGenerator();
    final KeyPair keyPairData = generator.generateKeyPair(privateKey);
    if (keyPairData != null) {
        return genEcPairFromKeyPair(keyPairData);
    }
    return null;
}
 
Example #27
Source File: TestKeyCodec.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Assert key rewrite fails without force option.
 *
 * @throws IOException - on I/O failure.
 */
@Test
public void testReWriteKey()
    throws Exception {
  KeyPair kp = keyGenerator.generateKey();
  KeyCodec pemWriter = new KeyCodec(securityConfig, component);
  SecurityConfig secConfig = pemWriter.getSecurityConfig();
  pemWriter.writeKey(kp);

  // Assert that rewriting of keys throws exception with valid messages.
  LambdaTestUtils
      .intercept(IOException.class, "Private Key file already exists.",
          () -> pemWriter.writeKey(kp));
  FileUtils.deleteQuietly(Paths.get(
      secConfig.getKeyLocation(component).toString() + "/" + secConfig
          .getPrivateKeyFileName()).toFile());
  LambdaTestUtils
      .intercept(IOException.class, "Public Key file already exists.",
          () -> pemWriter.writeKey(kp));
  FileUtils.deleteQuietly(Paths.get(
      secConfig.getKeyLocation(component).toString() + "/" + secConfig
          .getPublicKeyFileName()).toFile());

  // Should succeed now as both public and private key are deleted.
  pemWriter.writeKey(kp);
  // Should succeed with overwrite flag as true.
  pemWriter.writeKey(kp, true);

}
 
Example #28
Source File: JWTAuthOptionsFactory.java    From besu with Apache License 2.0 5 votes vote down vote up
private KeyPair generateJwtKeyPair() {
  final KeyPairGenerator keyGenerator;
  try {
    keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(2048);
  } catch (final NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }

  return keyGenerator.generateKeyPair();
}
 
Example #29
Source File: TestHDDSKeyGenerator.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * In this test we assert that size that we specified is used for Key
 * generation.
 * @throws NoSuchProviderException - On Error, due to missing Java
 * dependencies.
 * @throws NoSuchAlgorithmException - On Error,  due to missing Java
 * dependencies.
 */
@Test
public void testGenerateKeyWithSize() throws NoSuchProviderException,
    NoSuchAlgorithmException {
  HDDSKeyGenerator keyGen = new HDDSKeyGenerator(config.getConfiguration());
  KeyPair keyPair = keyGen.generateKey(4096);
  PublicKey publicKey = keyPair.getPublic();
  if(publicKey instanceof RSAPublicKey) {
    Assert.assertEquals(4096,
        ((RSAPublicKey)(publicKey)).getModulus().bitLength());
  }
}
 
Example #30
Source File: Correctness.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String SIGALG = "SHA1withRSA";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();

        SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
                Signature.getInstance(SIGALG));

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(so1);
        out.close();

        byte[] data = byteOut.toByteArray();

        SignedObject so2 = (SignedObject)new ObjectInputStream(
                new ByteArrayInputStream(data)).readObject();

        if (!so2.getObject().equals("Hello")) {
            throw new Exception("Content changed");
        }
        if (!so2.getAlgorithm().equals(SIGALG)) {
            throw new Exception("Signature algorithm unknown");
        }
        if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
            throw new Exception("Not verified");
        }
    }