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 Project: kareldb   Author: rayokota   File: SecureTestUtils.java    License: 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 Project: Wurst7   Author: Wurst-Imperium   File: Encryption.java    License: 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 Project: CompetitiveJava   Author: dubesar   File: SignatureExample.java    License: 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 Project: CapturePacket   Author: huanglqweiwei   File: RootCertificateGenerator.java    License: 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 #5
Source Project: openjsse   Author: openjsse   File: DHKeyExchange.java    License: 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 #6
Source Project: javasdk   Author: hyperchain   File: ECKey.java    License: 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 #7
Source Project: openjsse   Author: openjsse   File: RSAKeyExchange.java    License: 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 #8
Source Project: jlibra   Author: ketola   File: GenerateKeysExample.java    License: 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 #9
Source Project: NutzSite   Author: TomYule   File: RSAUtils.java    License: 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 #10
Source Project: hadoop-ozone   Author: apache   File: TestDefaultCertificateClient.java    License: 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 #11
Source Project: markdown-image-kit   Author: dong4j   File: AsymmetricKeyEncryptionClientDemo.java    License: 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 #12
Source Project: WeBASE-Sign   Author: WeBankFinTech   File: KeyPairUtils.java    License: 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 #13
Source Project: TencentKona-8   Author: Tencent   File: SolarisShortDSA.java    License: 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 #14
Source Project: TencentKona-8   Author: Tencent   File: FinalizeHalf.java    License: 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 #15
Source Project: dragonwell8_jdk   Author: alibaba   File: FinalizeHalf.java    License: 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 Project: openjsse   Author: openjsse   File: ECDHKeyExchange.java    License: 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 #17
/**
 * 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 #18
Source Project: grpc-nebula-java   Author: grpc-nebula   File: GoogleAuthLibraryCallCredentialsTest.java    License: 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 #19
Source Project: grpc-nebula-java   Author: grpc-nebula   File: GoogleAuthLibraryCallCredentialsTest.java    License: 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 #20
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: HTTPJwtAuthenticatorTest.java    License: 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 #21
Source Project: dragonwell8_jdk   Author: alibaba   File: TestCipherKeyWrapperTest.java    License: 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 #22
Source Project: TencentKona-8   Author: Tencent   File: SignatureTest.java    License: 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 #23
Source Project: InviZible   Author: Gedsh   File: UpdateCheck.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String RSASign(final String appSignature) {
    try {
        KeyPair kp = generateRSAKeyPair();
        publicKey = kp.getPublic();
        privateKey = kp.getPrivate();

        String signature = appSignature.trim() +
                convertKeyForPHP(publicKey.getEncoded()).trim() +
                appProcVersion.trim() +
                appVersion.trim() +
                "submit";

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(signature.getBytes(StandardCharsets.UTF_8));
        String hexBytes = bin2hex(digest);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] encryptedBytes = cipher.doFinal(hexBytes.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
    } catch (Exception e) {
        if (context != null) {
            if (MainActivity.modernDialog != null)
                ((MainActivity) context).showUpdateMessage(context.getText(R.string.update_fault).toString());
            new PrefManager(context).setStrPref("LastUpdateResult", context.getText(R.string.update_fault).toString());
        }
        Log.e(LOG_TAG, "RSASign function fault " + e.getMessage());
    }
    return null;
}
 
Example #24
Source Project: browserup-proxy   Author: browserup   File: RSAKeyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public KeyPair generate() {
    // obtain an RSA key pair generator for the specified key size
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(RSA_KEY_GEN_ALGORITHM);
        generator.initialize(keySize);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyGeneratorException("Unable to generate " + keySize + "-bit RSA public/private key pair", e);
    }

    return generator.generateKeyPair();
}
 
Example #25
Source Project: dragonwell8_jdk   Author: alibaba   File: Offsets.java    License: GNU General Public License v2.0 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;
    int keySize = 2048;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
        keySize = 256;
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
        if (algorithm.startsWith("SHAwith") ||
                algorithm.startsWith("SHA1with")) {
            keySize = 1024;
        }
    } else {
        throw new RuntimeException("Test doesn't support this signature "
                + "algorithm: " + algorithm);
    }

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

    return new Offsets(signature, pubkey, privkey, size, cleartext);
}
 
Example #26
Source Project: hop   Author: project-hop   File: CertificateGenEncryptUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test( expected = Exception.class )
public void testImproperSessionKeyEncryptionDecryption5() throws Exception {
  Key key = CertificateGenEncryptUtil.generateSingleKey();
  KeyPair kp = CertificateGenEncryptUtil.generateKeyPair();
  Key privateKey = kp.getPrivate();
  byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( kp.getPublic(), key );
  byte[] encryptedKey1 = new byte[ privateKey.getEncoded().length ];
  System.arraycopy( privateKey.getEncoded(), 0, encryptedKey1, 0, privateKey.getEncoded().length );
  encryptedKey1[ encryptedKey1.length - 1 ] = (byte) ( encryptedKey1[ encryptedKey1.length - 1 ] - 1 );
  CertificateGenEncryptUtil.decodeTransmittedKey( encryptedKey1, encryptedKey, true );
}
 
Example #27
Source Project: AndroidWallet   Author: Cocos-BCX   File: private_key.java    License: GNU General Public License v3.0 5 votes vote down vote up
private private_key(KeyPair ecKey) {
    BCECPrivateKey privateKey = (BCECPrivateKey) ecKey.getPrivate();
    byte[] privateKeyGenerate = privateKey.getD().toByteArray();
    if (privateKeyGenerate.length == 33) {
        System.arraycopy(privateKeyGenerate, 1, key_data, 0, key_data.length);
    } else {
        System.arraycopy(privateKeyGenerate, 0, key_data, 0, key_data.length);
    }
}
 
Example #28
Source Project: TencentKona-8   Author: Tencent   File: TestSignatureOidHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void runTest(OidAlgorithmPair oidAlgorithmPair, KeyPair keyPair)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    Signature sgAlgorithm =
            Signature.getInstance(oidAlgorithmPair.algorithm, provider);
    Signature sgOid = Signature.getInstance(oidAlgorithmPair.oid, provider);

    if (sgAlgorithm == null) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance failed.%n",
                oidAlgorithmPair.algorithm));
    }

    if (sgOid == null) {
        throw new RuntimeException(
                String.format("Test failed: OID %s getInstance failed.%n",
                        oidAlgorithmPair.oid));
    }

    if (!sgAlgorithm.getAlgorithm().equals(oidAlgorithmPair.algorithm)) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance "
                        + "doesn't generate expected algorithm.%n",
                oidAlgorithmPair.algorithm));
    }

    sgAlgorithm.initSign(keyPair.getPrivate());
    sgAlgorithm.update(INPUT);
    sgOid.initVerify(keyPair.getPublic());
    sgOid.update(INPUT);
    if (!sgOid.verify(sgAlgorithm.sign())) {
        throw new RuntimeException(
                "Signature verification failed unexpectedly");
    }
}
 
Example #29
Source Project: smartapp-sdk-java   Author: SmartThingsCommunity   File: HttpVerificationService.java    License: Apache License 2.0 5 votes vote down vote up
private VerifyResult verifyRequest(Authorization authorization, KeyPair pair, String method,
        String uri, Map<String, String> headers) {
    DefaultKeychain keychain = new DefaultKeychain();
    String fpKeyId = authorization.getKeyId().substring(1); // remove slash from front
    KeyId keyId;
    if (fpKeyId.startsWith("SmartThings")) {
        keyId = new UserFingerprintKeyId("SmartThings");
    } else {
        keyId = new FixedKeyId(authorization);
    }
    keychain.add(new SSHKey(KeyFormat.SSH_RSA, pair));
    Verifier verifier = new DefaultVerifier(keychain, keyId);

    Challenge challenge = new Challenge("<preemptive>", authorization.getHeaders(),
        Collections.unmodifiableList(Arrays.asList(authorization.getAlgorithm())));

    Set<String> signedHeaders = authorization.getHeaders().stream()
        .map(String::toLowerCase)
        .collect(Collectors.toSet());

    if (log.isDebugEnabled()) {
        log.debug("requestURI: " + uri);
    }

    RequestContent.Builder content = new RequestContent.Builder()
        .setRequestTarget(method, uri);

    headers.keySet().stream()
        .filter(headerName -> signedHeaders.contains(headerName.toLowerCase(Locale.ENGLISH)))
        .forEach(headerName -> content.addHeader(headerName, headers.get(headerName)));

    RequestContent requestContent = content.build();
    return verifier.verifyWithResult(challenge, requestContent, authorization);
}
 
Example #30
Source Project: hadoop-ozone   Author: apache   File: DefaultCertificateClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Bootstrap the client by creating keypair and storing it in configured
 * location.
 * */
protected void bootstrapClientKeys() throws CertificateException {
  Path keyPath = securityConfig.getKeyLocation(component);
  if (Files.notExists(keyPath)) {
    try {
      Files.createDirectories(keyPath);
    } catch (IOException e) {
      throw new CertificateException("Error while creating directories " +
          "for certificate storage.", BOOTSTRAP_ERROR);
    }
  }
  KeyPair keyPair = createKeyPair();
  privateKey = keyPair.getPrivate();
  publicKey = keyPair.getPublic();
}