Java Code Examples for java.security.KeyPair

The following are top voted examples for showing how to use java.security.KeyPair. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: rebase-android   File: BlackBox.java   Source Code and License 7 votes vote down vote up
/**
 * Creates a public and private key and stores it using the AndroidKeyStore,
 * so that only this application will be able to access the keys.
 */
@SuppressWarnings("deprecation")
public void createKeys() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    if (keyStore.containsAlias(alias)) {
        Log.d(TAG, "[containsAlias]");
        return;
    }

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
        .setAlias(alias)
        .setSubject(new X500Principal("CN=" + alias))
        .setSerialNumber(BigInteger.TEN)
        .setStartDate(start.getTime())
        .setEndDate(end.getTime())
        .build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE_RSA, ANDROID_KEY_STORE);
    generator.initialize(spec);
    KeyPair keyPair = generator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
}
 
Example 2
Project: xitk   File: KeyUtil.java   Source Code and License 7 votes vote down vote up
public static KeyPair generateECKeypair(ASN1ObjectIdentifier curveId, SecureRandom random)
        throws NoSuchAlgorithmException, NoSuchProviderException,
            InvalidAlgorithmParameterException {
    ParamUtil.requireNonNull("curveId", curveId);

    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveId.getId());
    KeyPairGenerator kpGen = getKeyPairGenerator("EC");
    synchronized (kpGen) {
        if (random == null) {
            kpGen.initialize(spec);
        } else {
            kpGen.initialize(spec, random);
        }
        return kpGen.generateKeyPair();
    }
}
 
Example 3
Project: AppCoins-ethereumj   File: ECKey.java   Source Code and License 7 votes vote down vote up
/**
 * 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());
    }
}
 
Example 4
Project: ipack   File: RainbowKeyPairGeneratorSpi.java   Source Code and License 7 votes vote down vote up
public KeyPair generateKeyPair()
{
    if (!initialised)
    {
        param = new RainbowKeyGenerationParameters(random, new RainbowParameters(new RainbowParameterSpec().getVi()));

        engine.init(param);
        initialised = true;
    }

    AsymmetricCipherKeyPair pair = engine.generateKeyPair();
    RainbowPublicKeyParameters pub = (RainbowPublicKeyParameters)pair.getPublic();
    RainbowPrivateKeyParameters priv = (RainbowPrivateKeyParameters)pair.getPrivate();

    return new KeyPair(new BCRainbowPublicKey(pub),
        new BCRainbowPrivateKey(priv));
}
 
Example 5
Project: L2J-Global   File: GameServerThread.java   Source Code and License 7 votes vote down vote up
public GameServerThread(Socket con)
{
	_connection = con;
	_connectionIp = con.getInetAddress().getHostAddress();
	try
	{
		_in = _connection.getInputStream();
		_out = new BufferedOutputStream(_connection.getOutputStream());
	}
	catch (IOException e)
	{
		_log.warning(getClass().getSimpleName() + ": " + e.getMessage());
	}
	final KeyPair pair = GameServerTable.getInstance().getKeyPair();
	_privateKey = (RSAPrivateKey) pair.getPrivate();
	_publicKey = (RSAPublicKey) pair.getPublic();
	_blowfish = new NewCrypt("_;v.]05-31!|+-%xT!^[$\00");
	setName(getClass().getSimpleName() + "-" + getId() + "@" + _connectionIp);
	start();
}
 
Example 6
Project: crypto4ora   File: Client.java   Source Code and License 7 votes vote down vote up
public static void test() throws Exception {
	KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    keyGen.initialize(512, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();
    Signature signature = Signature.getInstance("SHA1withRSA");

    signature.initSign(keyPair.getPrivate());

    byte[] message = "abc".getBytes();
    signature.update(message);

    byte[] sigBytes = signature.sign();
    signature.initVerify(keyPair.getPublic());
    signature.update(message);
    System.out.println(signature.verify(sigBytes));
	
}
 
Example 7
Project: BaseClient   File: CryptManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 8
Project: openjdk-jdk10   File: TestECDH2.java   Source Code and License 6 votes vote down vote up
private static void testKeyAgreement(KeyPair kpA, KeyPair kpB, Provider p)
    throws Exception {
    KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", p);
    ka1.init(kpA.getPrivate());
    ka1.doPhase(kpB.getPublic(), true);
    byte[] s1 = ka1.generateSecret();

    KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", p);
    ka2.init(kpB.getPrivate());
    ka2.doPhase(kpA.getPublic(), true);
    byte[] s2 = ka2.generateSecret();
    if (Arrays.equals(s1, s2) == false) {
        System.out.println("expected: " + toString(s1));
        System.out.println("actual:   " + toString(s2));
        throw new Exception("Generated secrets do not match");
    }
}
 
Example 9
Project: edge-jwt-sample   File: JWTValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testJWEWithRSAAESKey2() {
	String claimsJSON = sampleClaims();
	KeyPair rsaKeyPair = getRSAKeyPair();
	String jwt = jweEncrypt(claimsJSON, false, rsaKeyPair.getPublic(), "RSA_OAEP", "AES_128_GCM");
	String pemPrivateKey = getPEMPrivateKeyFromDER(rsaKeyPair.getPrivate());

	JWTValidator validator = 
		jweValidator(
			pemPrivateKey, "RSA_OAEP", "AES_128_GCM", 
			jwt, "edge-jwt-gen", "aud-1", "300");
	ExecutionResult result = validator.execute(this.mctx, this.ectx);

	verifySuccessResult(result);
	varifyClaims(this.mctx.getVariable(CLAIMS));
}
 
Example 10
Project: mi-firma-android   File: JseCryptoHelper.java   Source Code and License 6 votes vote down vote up
@Override
public KeyPair generateEcKeyPair(final EcCurve curveName) throws NoSuchAlgorithmException,
                                                                 InvalidAlgorithmParameterException {
	if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
		Security.addProvider(new BouncyCastleProvider());
	}
	KeyPairGenerator kpg;
	try {
		kpg = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); //$NON-NLS-1$
	}
	catch (final Exception e) {
		Logger.getLogger("es.gob.jmulticard").warning( //$NON-NLS-1$
			"No se ha podido obtener un generador de pares de claves de curva eliptica con SpongyCastle, se usara el generador por defecto: " + e //$NON-NLS-1$
		);
		kpg = KeyPairGenerator.getInstance("EC"); //$NON-NLS-1$
	}

	Logger.getLogger("es.gob.jmulticard").info( //$NON-NLS-1$
		"Seleccionado el siguiente generador de claves de curva eliptica: " + kpg.getClass().getName() //$NON-NLS-1$
	);

	final AlgorithmParameterSpec parameterSpec = new ECGenParameterSpec(curveName.toString());
	kpg.initialize(parameterSpec);
	return kpg.generateKeyPair();
}
 
Example 11
Project: edge-jwt-sample   File: JWTValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testJWEAndJWSWithRSAAndRSA() {
	String claimsJSON = sampleClaims();
	KeyPair rsaKeyPairSign = getRSAKeyPair();
	String pemPublicKeySign = getPEMPublicKeyFromDER(rsaKeyPairSign.getPublic());
	KeyPair rsaKeyPairEnc = getRSAKeyPair();
	String pemPrivateKeyEnc = getPEMPrivateKeyFromDER(rsaKeyPairEnc.getPrivate());
	
	String innerJWT = jwsSign(claimsJSON, rsaKeyPairSign.getPrivate(), "RSA_USING_SHA256");
	String jwt = jweEncrypt(innerJWT, true, rsaKeyPairEnc.getPublic(), "RSA_OAEP", "AES_128_GCM");

	JWTValidator validator = 
		validatorJWSAndJWE(
			pemPublicKeySign, "RSA_USING_SHA256",
			pemPrivateKeyEnc, "RSA_OAEP", "AES_128_GCM", 
			jwt, "edge-jwt-gen", "aud-1", "300");
	ExecutionResult result = validator.execute(this.mctx, this.ectx);

	verifySuccessResult(result);
	varifyClaims(this.mctx.getVariable(CLAIMS));
}
 
Example 12
Project: firebase-admin-java   File: FirebaseTokenFactoryTest.java   Source Code and License 6 votes vote down vote up
@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())));
}
 
Example 13
Project: BaseClient   File: CryptManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 14
Project: outcomes   File: Main.java   Source Code and License 6 votes vote down vote up
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));

    }
 
Example 15
Project: xmlrss   File: AbstractRSSTest.java   Source Code and License 6 votes vote down vote up
public AbstractRSSTest(String algorithm, Provider provider, KeyPair keyPair) {
    Security.insertProviderAt(provider, 1);
    this.algorithm = algorithm;
    this.providerName = provider.getName();
    this.provider = provider;
    AbstractRSSTest.keyPair = keyPair;
}
 
Example 16
Project: ditb   File: KeyStoreTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Create a self-signed X.509 Certificate.
 *
 * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) 
    throws CertificateEncodingException, InvalidKeyException, IllegalStateException, 
    NoSuchProviderException, NoSuchAlgorithmException, SignatureException {
  Date from = new Date();
  Date to = new Date(from.getTime() + days * 86400000l);
  BigInteger sn = new BigInteger(64, new SecureRandom());
  KeyPair keyPair = pair;
  X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
  X500Principal  dnName = new X500Principal(dn);

  certGen.setSerialNumber(sn);
  certGen.setIssuerDN(dnName);
  certGen.setNotBefore(from);
  certGen.setNotAfter(to);
  certGen.setSubjectDN(dnName);
  certGen.setPublicKey(keyPair.getPublic());
  certGen.setSignatureAlgorithm(algorithm);
  X509Certificate cert = certGen.generate(pair.getPrivate());
  return cert;
}
 
Example 17
Project: edge-jwt-sample   File: JWTValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testJWEAndJWSWithRSAAndHMAC() {
	String claimsJSON = sampleClaims();
	SecretKey keySign = getHmacSHA256Key();
	KeyPair rsaKeyPairEnc = getRSAKeyPair();
	String pemPrivateKeyEnc = getPEMPrivateKeyFromDER(rsaKeyPairEnc.getPrivate());
	
	String innerJWT = jwsSign(claimsJSON, keySign, "HMAC_SHA256");
	String jwt = jweEncrypt(innerJWT, true, rsaKeyPairEnc.getPublic(), "RSA_OAEP", "AES_128_GCM");

	JWTValidator validator = 
		validatorJWSAndJWE(
			keyToString(keySign), "HMAC_SHA256",
			pemPrivateKeyEnc, "RSA_OAEP", "AES_128_GCM", 
			jwt, "edge-jwt-gen", "aud-1", "300");
	ExecutionResult result = validator.execute(this.mctx, this.ectx);

	verifySuccessResult(result);
	varifyClaims(this.mctx.getVariable(CLAIMS));
}
 
Example 18
Project: openjdk-jdk10   File: TestKeyFactory.java   Source Code and License 6 votes vote down vote up
@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());
    }
}
 
Example 19
Project: Encryption   File: TestRSA.java   Source Code and License 6 votes vote down vote up
private static void testRSA_Async_decrypt(KeyPair key, String message){

        Encoder.BuilderRSA()
                .message(message)
                .method(RSA.Method.RSA_ECB_OAEP_with_MD5_and_MGF1_PADDING)
                .key(key)
                .encryptCallBack(new EncodeCallback() {
                    @Override
                    public void onSuccess(String result) {
                        System.out.println("decryptAsync RSA with " + RSA.Method.RSA_ECB_OAEP_with_MD5_and_MGF1_PADDING + " = " + result);
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        System.out.println("decryptAsync RSA error");
                        e.printStackTrace();
                    }
                })
                .decryptAsync();
    }
 
Example 20
Project: wolfcrypt-jni   File: EccTest.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 21
Project: hadoop-oss   File: TestReloadingX509TrustManager.java   Source Code and License 6 votes vote down vote up
@Test
public void testReloadMissingTrustStore() throws Exception {
  KeyPair kp = generateKeyPair("RSA");
  cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
  cert2 = generateCertificate("CN=Cert2", kp, 30, "SHA1withRSA");
  String truststoreLocation = BASEDIR + "/testmissing.jks";
  createTrustStore(truststoreLocation, "password", "cert1", cert1);

  ReloadingX509TrustManager tm =
    new ReloadingX509TrustManager("jks", truststoreLocation, "password", 10);
  try {
    tm.init();
    assertEquals(1, tm.getAcceptedIssuers().length);
    X509Certificate cert = tm.getAcceptedIssuers()[0];
    new File(truststoreLocation).delete();

    // Wait so that the file modification time is different
    Thread.sleep((tm.getReloadInterval() + 200));

    assertEquals(1, tm.getAcceptedIssuers().length);
    assertEquals(cert, tm.getAcceptedIssuers()[0]);
  } finally {
    tm.destroy();
  }
}
 
Example 22
Project: mobile-store   File: LocalRepoKeyStore.java   Source Code and License 6 votes vote down vote up
public void setupHTTPSCertificate() {
    try {
        // Get the existing private/public keypair to use for the HTTPS cert
        KeyPair kerplappKeypair = getKerplappKeypair();

        /*
         * Once we have an IP address, that can be used as the hostname. We
         * can generate a self signed cert with a valid CN field to stash
         * into the keystore in a predictable place. If the IP address
         * changes we should run this method again to stomp old
         * HTTPS_CERT_ALIAS entries.
         */
        X500Name subject = new X500Name("CN=" + FDroidApp.ipAddressString);
        Certificate indexCert = generateSelfSignedCertChain(kerplappKeypair, subject,
                FDroidApp.ipAddressString);
        addToStore(HTTP_CERT_ALIAS, kerplappKeypair, indexCert);
    } catch (Exception e) {
        Log.e(TAG, "Failed to setup HTTPS certificate", e);
    }
}
 
Example 23
Project: openjdk-jdk10   File: SupportedDHKeys.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 24
Project: DecompiledMinecraft   File: CryptManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 25
Project: edge-jwt-sample   File: JWTValidatorTest.java   Source Code and License 5 votes vote down vote up
private KeyPair getRSAKeyPair() {
	try {
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(2048);
		return keyGen.generateKeyPair();
	} catch (Exception e) {
		System.out.println("Unable to initialize RSA key pair.");
		e.printStackTrace();
		return null;
	}
}
 
Example 26
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
    * Create a random 1024 bit RSA key pair
    */
   public static KeyPair generateRSAKeyPair()
       throws Exception
{
   	Security
	.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
       KeyPairGenerator  kpGen = KeyPairGenerator.getInstance("RSA", "BC");
   
       kpGen.initialize(1024, new SecureRandom());
   
       return kpGen.generateKeyPair();
}
 
Example 27
Project: asch-java   File: TransactionBuilder.java   Source Code and License 5 votes vote down vote up
public TransactionInfo buildSignature(String secret, String secondSecret) throws  SecurityException{
    KeyPair keyPair = getSecurity().generateKeyPair(secret);
    KeyPair secondKeyPair = getSecurity().generateKeyPair(secondSecret);

    TransactionInfo transaction =  newTransaction(
            TransactionType.Signature,
            0L,
            AschConst.Fees.SECOND_SIGNATURE,
            keyPair.getPublic())
            .setAsset(new SignatureAssetInfo(getSecurity().encodePublicKey(secondKeyPair.getPublic())));

    return signatureAndGenerateTransactionId(transaction, keyPair.getPrivate(), null);

}
 
Example 28
Project: openjdk-jdk10   File: GenerateRSAKeyPair.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        RSAKeyGenParameterSpec rsaSpec =
        new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
        kpg.initialize(rsaSpec);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
Example 29
Project: crypto-shuffle   File: JsonUtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void multiEncryptionSerializationTest() {
    Set<KeyPair> keyPairs = generateKeyPairs(3);
    final MultiEncryption multiEncryption
            = new MultiEncryption(key24, keyPairs.stream().map(KeyPair::getPublic).collect(Collectors.toList()));
    final ObjectNode jsonObject = (ObjectNode) JsonUtil.multiEncryptionToJson(multiEncryption);
    jsonObject.get(JsonUtil.ENCRYPTION_ALGORITHM_NAME).asText();
    assertEquals(JsonUtil.VERSION1_0, jsonObject.get(JsonUtil.VERSION_NAME).asText());
    assertEquals("RSA", jsonObject.get(JsonUtil.ENCRYPTION_ALGORITHM_NAME).asText());
    final ObjectNode keysObject = (ObjectNode) jsonObject.get(JsonUtil.ENCRYPTIONS_NAME);
    assertEquals(3, keysObject.size());
}
 
Example 30
Project: Myst   File: Util.java   Source Code and License 5 votes vote down vote up
public static ECPoint randECPoint() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    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();
}
 
Example 31
Project: 19porn   File: Codec.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化密钥
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> initKey() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator
            .getInstance(Algorithm.RSA.getType());
    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 32
Project: asch-java   File: TransactionBuilder.java   Source Code and License 5 votes vote down vote up
public TransactionInfo buildInTransfer(String dappId, String currency, long amount, String secret, String secondSecret)throws SecurityException {

        KeyPair keyPair = getSecurity().generateKeyPair(secret);

        TransactionInfo transaction =  newTransaction(
                TransactionType.InTransfer,
                currency.equals("XAS") ? amount : 0l,
                AschConst.Fees.TRANSFER,
                keyPair.getPublic())
                .setAsset(new InTransferAssetInfo(dappId, currency,currency.equals("XAS") ? 0l : amount));

        return signatureAndGenerateTransactionId(transaction, keyPair.getPrivate(), secondSecret);

    }
 
Example 33
Project: pac4j-plus   File: JWKHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Build the RSA key pair from the JWK JSON.
 *
 * @param json the json
 * @return the key pair
 */
public static KeyPair buildRSAKeyPairFromJwk(final String json) {
    CommonHelper.assertNotBlank("json", json);

    try {
        final RSAKey rsaKey = RSAKey.parse(json);
        return rsaKey.toKeyPair();
    } catch (final JOSEException | ParseException e) {
        throw new TechnicalException(e);
    }
}
 
Example 34
Project: crypto-shuffle   File: JsonUtilTest.java   Source Code and License 5 votes vote down vote up
@Before
public void createKeyShardSet() {
    try {
        keyPairs5 = generateKeyPairs(5);
        keyPairs3 = generateKeyPairs(3);
        final KeyShardSet.KeyShardingSetBuilder builder = KeyShardSet.newBuilder(AsymmetricEncryptionAlgorithm.RSA);
        final Set<PublicKey> publicKeys5 = keyPairs5.stream().map(KeyPair::getPublic).collect(Collectors.toSet());
        final Set<PublicKey> publicKeys3 = keyPairs3.stream().map(KeyPair::getPublic).collect(Collectors.toSet());
        keyShardSet = builder.addKeyGroup(2,  publicKeys5).addKeyGroup(3,  publicKeys3).build(key4800);
    } catch (Throwable e) {
        System.err.println("Before");
        e.printStackTrace();
        throw e;
    }
}
 
Example 35
Project: openjdk-jdk10   File: SignatureTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    int testSize = Integer.parseInt(args[0]);

    byte[] data = new byte[100];
    IntStream.range(0, data.length).forEach(j -> {
        data[j] = (byte) j;
    });

    // 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
            -> Arrays.stream(SIGN_ALG).forEach(testAlg -> {
        try {
            checkSignature(data, (PublicKey) pub, (PrivateKey) priv,
                    testAlg);
        } catch (NoSuchAlgorithmException | InvalidKeyException |
                SignatureException | NoSuchProviderException ex) {
            throw new RuntimeException(ex);
        }
    }
    )));

}
 
Example 36
Project: JWaves   File: Address.java   Source Code and License 5 votes vote down vote up
/**
 * Create new address.
 *
 * @param chain chain.
 * @param n     world count.
 * @return new address.
 * @throws IOException
 */
public static Address createNew(@NotNull final String chain, final int n) throws IOException {
    if (n <= 0)
        throw new IllegalArgumentException("n must be positive");

    final File file = new File("src/main/resources/words.json");
    final ObjectMapper mapper = new ObjectMapper();
    final CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, String.class);
    final List<String> wordList = mapper.readValue(file, type);

    final StringBuilder words = new StringBuilder();
    final Random rand = new Random();
    for (int i = 0; i < n; i++) {
        int index = rand.nextInt(wordList.size());
        words.append(wordList.get(index));
        if (i < n - 1) {
            words.append(" ");
        }

        wordList.remove(index);
    }

    final String seed = words.toString();
    byte[] seedEncode = seed.getBytes(StandardCharsets.UTF_8);

    final byte[] seedHash = Crypto.hashChain(seedEncode);
    final byte[] accountSeedHash = Crypto.sha256(seedHash);
    final Curve25519KeyPairGenerator gen = new Curve25519KeyPairGenerator();
    final KeyPair pair = gen.generateKeyPair(accountSeedHash);

    return generate(pair, seed, chain);
}
 
Example 37
Project: GroupControlDroidClient   File: RSAUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 生成公钥和私钥
 * 
 * @throws NoSuchAlgorithmException
 * 
 */
public static HashMap<String, Object> getKeys()
		throws NoSuchAlgorithmException {
	HashMap<String, Object> map = new HashMap<String, Object>();
	KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
	keyPairGen.initialize(1024,new SecureRandom());
	KeyPair keyPair = keyPairGen.generateKeyPair();
	RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
	RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
	map.put("public", publicKey);
	map.put("private", privateKey);
	return map;
}
 
Example 38
Project: openjdk-jdk10   File: Correctness.java   Source Code and License 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 39
Project: Spring-Security-Third-Edition   File: OAuth2AuthorizationServerConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    KeyPair keyPair = new KeyStoreKeyFactory(
            new ClassPathResource(keystore),
            keyStorePass.toCharArray()
    ).getKeyPair(keyPairAlias);

    converter.setKeyPair(keyPair);
    return converter;
}
 
Example 40
Project: openjdk-jdk10   File: Offsets.java   Source Code and License 5 votes vote down vote up
static Offsets init(String provider, String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    // fill the cleartext data with random bytes
    byte[] cleartext = new byte[100];
    RandomFactory.getRandom().nextBytes(cleartext);

    // NONEwith requires input to be of 20 bytes
    int size = algorithm.contains("NONEwith") ? 20 : 100;

    // create signature instance
    Signature signature = Signature.getInstance(algorithm, provider);

    String keyAlgo;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
    } else {
        throw new RuntimeException("Test doesn't support this signature "
                + "algorithm: " + algorithm);
    }

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubkey = kp.getPublic();
    PrivateKey privkey = kp.getPrivate();

    return new Offsets(signature, pubkey, privkey, size, cleartext);
}