public static void main(String[] args) throws Exception { // Generate 20 serial numbers with dup and a special order int count = 20; BigInteger[] serials = new BigInteger[count]; for (int i = 0; i < count; i++) { serials[i] = BigInteger.valueOf(i * 7 % 10); } // Generates a CRL X509CRLEntry[] badCerts = new X509CRLEntry[count]; for (int i = 0; i < count; i++) { badCerts[i] = new X509CRLEntryImpl(serials[i], new Date(System.currentTimeMillis() + i * 1000)); } X500Name owner = new X500Name("CN=CA"); X509CRLImpl crl = new X509CRLImpl(owner, new Date(), new Date(), badCerts); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); crl.sign(kpg.genKeyPair().getPrivate(), "SHA1withRSA"); byte[] data = crl.getEncodedInternal(); // Check the encoding checkData(crl, data, serials); // Load a CRL from raw data CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CRLImpl crl2 = (X509CRLImpl) cf.generateCRL(new ByteArrayInputStream(data)); // Check the encoding again data = crl2.getEncodedInternal(); checkData(crl2, data, serials); }
public static void main(String[] args) throws Exception { byte[] input = new byte[] {(byte) 0xbe, (byte) 0xef}; Cipher cipher = Cipher.getInstance("ElGamal/None/NoPadding", "BC"); SecureRandom random = Utils.createFixedRandom(); // create the keys KeyPairGenerator generator = KeyPairGenerator.getInstance("ElGamal", "BC"); generator.initialize(256, random); KeyPair pair = generator.generateKeyPair(); Key pubKey = pair.getPublic(); Key privKey = pair.getPrivate(); System.out.println("input : " + Utils.toHex(input)); // encryption step cipher.init(Cipher.ENCRYPT_MODE, pubKey, random); byte[] cipherText = cipher.doFinal(input); System.out.println("cipher: " + Utils.toHex(cipherText)); // decryption step cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] plainText = cipher.doFinal(cipherText); System.out.println("plain : " + Utils.toHex(plainText)); }
@Override protected Boolean doInBackground(String... params) { final String alias = params[0]; try { /* * Generate a new EC key pair entry in the Android Keystore by * using the KeyPairGenerator API. The private key can only be * used for signing or verification and only with SHA-256 or * SHA-512 as the message digest. */ KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore"); kpg.initialize( new KeyGenParameterSpec.Builder( alias, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) .build()); KeyPair kp = kpg.generateKeyPair(); return true; } catch (NoSuchAlgorithmException e) { Log.w(TAG, "Could not generate key", e); return false; } catch (InvalidAlgorithmParameterException e) { Log.w(TAG, "Could not generate key", e); return false; } catch (NoSuchProviderException e) { Log.w(TAG, "Could not generate key", e); return false; } }
/** 生成密钥对 */ public static Map<String, String> generateKeyPair() throws Exception { /** RSA算法要求有一个可信任的随机数源 */ SecureRandom sr = new SecureRandom(); /** 为RSA算法创建一个KeyPairGenerator对象 */ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ kpg.initialize(KEYSIZE, sr); /** 生成密匙对 */ KeyPair kp = kpg.generateKeyPair(); /** 得到公钥 */ Key publicKey = kp.getPublic(); byte[] publicKeyBytes = publicKey.getEncoded(); String pub = new String(Base64.encodeBase64(publicKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING); /** 得到私钥 */ Key privateKey = kp.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String pri = new String(Base64.encodeBase64(privateKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING); Map<String, String> map = new HashMap<String, String>(); map.put("publicKey", pub); map.put("privateKey", pri); RSAPublicKey rsp = (RSAPublicKey) kp.getPublic(); BigInteger bint = rsp.getModulus(); byte[] b = bint.toByteArray(); byte[] deBase64Value = Base64.encodeBase64(b); String retValue = new String(deBase64Value); map.put("modulus", retValue); return map; }
public KeyPair generateKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ds().network.getProperty("PKAlgo", "DSA")); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(1024, random); return keyGen.generateKeyPair(); }
private void sealedObjectTest() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES"); kpg.initialize(new ECGenParameterSpec("secp256r1")); KeyPair keyPair = kpg.generateKeyPair(); Cipher cipher = Cipher.getInstance("ECIES"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); String toEncrypt = "Hello"; // Check that cipher works ok cipher.doFinal(toEncrypt.getBytes()); // Using a SealedObject to encrypt the same string fails with a NullPointerException SealedObject sealedObject = new SealedObject(toEncrypt, cipher); cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); String result = (String) sealedObject.getObject(cipher); isTrue("result wrong", result.equals(toEncrypt)); result = (String) sealedObject.getObject(keyPair.getPrivate()); isTrue("result wrong", result.equals(toEncrypt)); }
public void generateLocalKeyPair(String fullUserId) { String userId = Address.stripResource(fullUserId); OtrDebugLogger.log("generating local key pair for: " + userId); KeyPair keyPair; try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALG); kpg.initialize(KEY_SIZE); keyPair = kpg.genKeyPair(); } catch (NoSuchAlgorithmException e) { OtrDebugLogger.log("no such algorithm", e); return; } OtrDebugLogger.log("SUCCESS! generating local key pair for: " + userId); // Store Private Key. PrivateKey privKey = keyPair.getPrivate(); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded()); this.store.setProperty(userId + ".privateKey", pkcs8EncodedKeySpec.getEncoded()); // Store Public Key. PublicKey pubKey = keyPair.getPublic(); storeLocalPublicKey(userId, pubKey); store.save(); }
public boolean generateKeys() { PublicKey keyPub; PrivateKey keyPri; SecureRandom rand; Security.addProvider(new ABAProvider()); rand = new SecureRandom(); rand.setSeed(System.currentTimeMillis()); try { KeyPairGenerator fact; KeyPair keyPair; fact = KeyPairGenerator.getInstance("RSA", "ABA"); fact.initialize(1024, rand); keyPair = fact.generateKeyPair(); keyPub = keyPair.getPublic(); keyPri = keyPair.getPrivate(); pubKey = bytesToHexStr(keyPub.getEncoded()); priKey = bytesToHexStr(keyPri.getEncoded()); } catch (Exception e) { return false; } return true; }
@PostConstruct public void create() throws Exception { Realm cd = new Realm(REALM_CD_NAME); Realm storedRealm = partitionManager.getPartition(Realm.class, cd.getName()); if (storedRealm == null) { cd.setEnforceSSL(true); KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); cd.setPrivateKey(keyPair.getPrivate().getEncoded()); cd.setPublickKey(keyPair.getPublic().getEncoded()); cd.setNumberFailedLoginAttempts(3); partitionManager.add(cd); IdentityManager cdIdentityManager = partitionManager.createIdentityManager(cd); Role Administrator = new Role("Administrator"); Role Customer = new Role("Customer"); Role Consumer = new Role("Consumer"); Role Vendor = new Role("Vendor"); Role Contacts = new Role("Contacts"); cdIdentityManager.add(Administrator); cdIdentityManager.add(Customer); cdIdentityManager.add(Consumer); cdIdentityManager.add(Vendor); cdIdentityManager.add(Contacts); User user = new User("admin"); cdIdentityManager.add(user); Password password = new Password("admin"); cdIdentityManager.updateCredential(user, password); RelationshipManager relationshipManager = partitionManager.createRelationshipManager(); relationshipManager.add(new Grant(user, Administrator)); Realm cdcustomer = new Realm(REALM_CDCustomer_NAME); Realm customerRealm = partitionManager.getPartition(Realm.class, cdcustomer.getName()); if (customerRealm == null) { cdcustomer.setEnforceSSL(true); KeyPair keyPaircustomer = KeyPairGenerator.getInstance("RSA").generateKeyPair(); cdcustomer.setPrivateKey(keyPaircustomer.getPrivate().getEncoded()); cdcustomer.setPublickKey(keyPaircustomer.getPublic().getEncoded()); cdcustomer.setNumberFailedLoginAttempts(3); partitionManager.add(cdcustomer); IdentityManager cdIdentityManagercst = partitionManager.createIdentityManager(cdcustomer); User customer = new User("customer"); cdIdentityManagercst.add(customer); Password demo = new Password("demo"); cdIdentityManagercst.updateCredential(customer, demo); relationshipManager.add(new Grant(customer, Customer)); User consumer = new User("consumer"); cdIdentityManagercst.add(consumer); cdIdentityManagercst.updateCredential(consumer, demo); relationshipManager.add(new Grant(consumer, Consumer)); } } }
@Override public void setAlgorithm(KeyAgreementType dhMode) { if (keyType != null && keyType.keyType == dhMode.keyType) return; keyType = dhMode; KeyPairGenerator kpg = null; try { switch (keyType.keyType) { case KeyAgreementType.DH_MODE_DH3K: algorithm = "DH"; kpg = KeyPairGenerator.getInstance(algorithm, "ZBC"); kpg.initialize(576); keyPair = kpg.genKeyPair(); break; case KeyAgreementType.DH_MODE_EC25: algorithm = "ECDH"; kpg = KeyPairGenerator.getInstance(algorithm, "ZBC"); // kpg.initialize(256); kpg.initialize(ECNamedCurveTable.getParameterSpec("P-256")); keyPair = kpg.genKeyPair(); break; case KeyAgreementType.DH_MODE_EC38: algorithm = "ECDH"; kpg = KeyPairGenerator.getInstance(algorithm, "ZBC"); // kpg.initialize(384); kpg.initialize(ECNamedCurveTable.getParameterSpec("P-384")); keyPair = kpg.genKeyPair(); break; default: break; } keyFactory = KeyFactory.getInstance(algorithm, "ZBC"); } catch (Exception e) { e.printStackTrace(); } }
/* * Get a temporary RSA KeyPair. */ KeyPair getRSAKeyPair(boolean export, SecureRandom random) { int length, index; if (ExportControl.hasStrongCrypto && !export) { length = 1024; index = INDEX_RSA512; } else { length = 512; index = INDEX_RSA1024; } KeyPair kp; EphemeralKeyPair ekp = keys[index]; synchronized (ekp) { kp = ekp.getKeyPair(); if (kp == null) { try { KeyPairGenerator kgen = KeyPairGenerator.getInstance("RSA"); kgen.initialize(length, random); ekp = new EphemeralKeyPair(kgen.genKeyPair()); kp = ekp.getKeyPair(); keys[index] = ekp; } catch (Exception e) { // ignore } } } return kp; }
public void main(Provider p) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p); kpg.initialize(512); KeyPair kp = kpg.generateKeyPair(); PrivateKey privateKey = kp.getPrivate(); PublicKey publicKey = kp.getPublic(); Signature sig = Signature.getInstance("MD5withRSA", p); byte[] data = new byte[10 * 1024]; new Random().nextBytes(data); sig.initSign(privateKey); sig.initSign(privateKey); sig.update(data); sig.initSign(privateKey); sig.update(data); byte[] signature = sig.sign(); sig.update(data); sig.initSign(privateKey); sig.update(data); sig.sign(); sig.sign(); sig.initSign(privateKey); sig.sign(); System.out.println("All tests passed"); }
public void testProtectedMessage() throws Exception { KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC); kGen.initialize(512); KeyPair kp = kGen.generateKeyPair(); X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test"); GeneralName sender = new GeneralName(new X500Name("CN=Sender")); GeneralName recipient = new GeneralName(new X500Name("CN=Recip")); ContentSigner signer = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(kp.getPrivate()); ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient) .setBody( new PKIBody( PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence())))) .addCMPCertificate(cert) .build(signer); X509Certificate jcaCert = new JcaX509CertificateConverter() .setProvider(BC) .getCertificate(message.getCertificates()[0]); ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().setProvider(BC).build(jcaCert.getPublicKey()); assertTrue(message.verify(verifierProvider)); assertEquals(sender, message.getHeader().getSender()); assertEquals(recipient, message.getHeader().getRecipient()); }
public static void main(String[] args) throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair par = keyGen.generateKeyPair(); prk = par.getPrivate(); pbk = par.getPublic(); Registry reg = null; System.out.println("Creando conexion remota"); try { reg = LocateRegistry.createRegistry(5555); } catch (Exception e) { e.printStackTrace(); } System.out.println("Creando objeto servidor"); Servidor s = new Servidor(); try { reg.rebind("Operaciones", (InterfaceRemota) UnicastRemoteObject.exportObject(s, 0)); } catch (Exception e) { e.printStackTrace(); } while (true) { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex); } } }
private KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize( new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); return keyPairGenerator.generateKeyPair(); }
public void testMacProtectedMessage() throws Exception { KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC); kGen.initialize(512); KeyPair kp = kGen.generateKeyPair(); X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test"); GeneralName sender = new GeneralName(new X500Name("CN=Sender")); GeneralName recipient = new GeneralName(new X500Name("CN=Recip")); ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient) .setBody( new PKIBody( PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence())))) .addCMPCertificate(cert) .build( new PKMACBuilder(new JcePKMACValuesCalculator().setProvider(BC)) .build("secret".toCharArray())); PKMACBuilder pkMacBuilder = new PKMACBuilder(new JcePKMACValuesCalculator().setProvider(BC)); assertTrue(message.verify(pkMacBuilder, "secret".toCharArray())); assertEquals(sender, message.getHeader().getSender()); assertEquals(recipient, message.getHeader().getRecipient()); }
@Test public void testKeygenToFileOutputStream() throws NoSuchAlgorithmException, NoSuchProviderException, IOException { final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey priv = pair.getPrivate(); final PublicKey pub = pair.getPublic(); // Write the private key to a file FileOutputStream privOS = new FileOutputStream("RSAPrivateKey.key"); Assert.assertNotNull(privOS); privOS.write(priv.getEncoded()); privOS.close(); // Write the private key to a file FileOutputStream publicOS = new FileOutputStream("RSAPublicKey.key"); Assert.assertNotNull(publicOS); publicOS.write(pub.getEncoded()); publicOS.close(); }
public static ECPublicKey PrivateKeytoECPublicKey(byte[] privateKey) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException { KeyPairGenerator kpg = null; kpg = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec gps = new ECGenParameterSpec("secp256k1"); // NIST P-256 kpg.initialize(gps); KeyPair apair = kpg.generateKeyPair(); ECPublicKey apub = (ECPublicKey) apair.getPublic(); ECParameterSpec aspec = apub.getParams(); byte[] publicKeyb = Address.privateKeyToPublicKey(Utils.toHex(privateKey), false); byte[] publicKeybx = new byte[32]; byte[] publicKeyby = new byte[32]; System.arraycopy(publicKeyb, 1, publicKeybx, 0, 32); System.arraycopy(publicKeyb, 33, publicKeyby, 0, 32); BigInteger x = new BigInteger(1, publicKeybx); BigInteger y = new BigInteger(1, publicKeyby); java.security.spec.ECPoint cpoint = new java.security.spec.ECPoint(x, y); ECPublicKeySpec cpubs = new ECPublicKeySpec(cpoint, aspec); ECPublicKey cpub = null; KeyFactory kfa = null; kfa = KeyFactory.getInstance("EC"); return cpub = (ECPublicKey) kfa.generatePublic(cpubs); }
private static String csr() { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair keyPair = keyGen.generateKeyPair(); X500Principal subject = new X500Principal( "CN = edea87b4-034d-48dc-94dd-e7cdcfdde370/10562468, OU = fgdfgretertgdfg, O = VW, L = US"); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic()); PKCS10CertificationRequest csr = builder.build(signer); String type = "CERTIFICATE REQUEST"; PemObject pem = new PemObject(type, csr.getEncoded()); StringWriter str = new StringWriter(); PEMWriter pemWriter = new PEMWriter(str); pemWriter.writeObject(pem); pemWriter.close(); str.close(); Log.d("Test", "" + str); return Base64Util.getStringAsBase64(str.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (OperatorCreationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
/** This method generates public and private keys. */ public static void generateKey() throws Exception { KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA); gen.initialize(512, new SecureRandom()); KeyPair keyPair = gen.generateKeyPair(); pubKey = keyPair.getPublic(); priKey = keyPair.getPrivate(); }
@Test public void testApply() { final Crypto crypto = createMock(Crypto.class); KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class); final SecureRandom secureRandom = createMock(SecureRandom.class); expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator); rsaKeyPairGenerator.initialize(2048, secureRandom); expect(rsaKeyPairGenerator.genKeyPair()).andReturn(keyPair); replay(crypto, rsaKeyPairGenerator, secureRandom); RsaSshKeyPairGenerator supplier = Guice.createInjector( new AbstractModule() { protected void configure() { bind(Crypto.class).toInstance(crypto); bind(SecureRandom.class).toInstance(secureRandom); } }) .getInstance(RsaSshKeyPairGenerator.class); assertEquals( supplier.get(), ImmutableMap.of( "public", openSshKey, "private", PRIVATE_KEY.replaceAll("\n", lineSeparator))); verify(crypto, rsaKeyPairGenerator, secureRandom); }
public static void main(String[] args) { try { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DSA"); paramGen.init(1024); AlgorithmParameters params = paramGen.generateParameters(); DSAParameterSpec dsaParameterSpec = params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(dsaParameterSpec); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); saveKey("BpubKey", publicKey); saveKey("BprivKey", privateKey); } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidAlgorithmParameterException e) { e.printStackTrace(); } }
public void init(int key_size) throws Exception { String name = null; if (key_size == 256) name = "secp256r1"; else if (key_size == 384) name = "secp384r1"; else if (key_size == 521) name = "secp521r1"; else throw new JSchException("unsupported key size: " + key_size); for (int i = 0; i < 1000; i++) { KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec ecsp = new ECGenParameterSpec(name); kpg.initialize(ecsp); KeyPair kp = kpg.genKeyPair(); prvKey = (ECPrivateKey) kp.getPrivate(); pubKey = (ECPublicKey) kp.getPublic(); params = pubKey.getParams(); d = ((ECPrivateKey) prvKey).getS().toByteArray(); ECPoint w = pubKey.getW(); r = w.getAffineX().toByteArray(); s = w.getAffineY().toByteArray(); if (r.length != s.length) continue; if (key_size == 256 && r.length == 32) break; if (key_size == 384 && r.length == 48) break; if (key_size == 521 && r.length == 66) break; } if (d.length < r.length) { d = insert0(d); } }
private void testKeyFactory() throws Exception { KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC"); ECCurve curve = new ECCurve.Fp( new BigInteger( "883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger( "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint( Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger( "883423532389192164791648750360308884807550341691627752275345424702807307")); // n ConfigurableProvider config = (ConfigurableProvider) Security.getProvider("SC"); config.setParameter(ConfigurableProvider.EC_IMPLICITLY_CA, ecSpec); g.initialize(null, new SecureRandom()); KeyPair p = g.generateKeyPair(); ECPrivateKey sKey = (ECPrivateKey) p.getPrivate(); ECPublicKey vKey = (ECPublicKey) p.getPublic(); KeyFactory fact = KeyFactory.getInstance("ECDSA", "SC"); vKey = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), null)); sKey = (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), null)); testECDSA(sKey, vKey); testBCParamsAndQ(sKey, vKey); testEC5Params(sKey, vKey); testEncoding(sKey, vKey); ECPublicKey vKey2 = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), ecSpec)); ECPrivateKey sKey2 = (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), ecSpec)); if (!vKey.equals(vKey2) || vKey.hashCode() != vKey2.hashCode()) { fail("private equals/hashCode failed"); } if (!sKey.equals(sKey2) || sKey.hashCode() != sKey2.hashCode()) { fail("private equals/hashCode failed"); } // check we can get specs. fact.getKeySpec(vKey, java.security.spec.ECPublicKeySpec.class); fact.getKeySpec(sKey, java.security.spec.ECPrivateKeySpec.class); }
public void run() { try { ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); BigInteger bg = dhSpec.getG(); BigInteger bp = dhSpec.getP(); oos.writeObject(bg); oos.writeObject(bp); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(1024); KeyPair kpa = (KeyPair) ois.readObject(); KeyAgreement dh = KeyAgreement.getInstance("DH"); KeyPair kp = kpg.generateKeyPair(); oos.writeObject(kp); dh.init(kp.getPrivate()); Key pk = dh.doPhase(kpa.getPublic(), true); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); byte[] rawbits = sha256.digest(dh.generateSecret()); Cipher c = Cipher.getInstance(CIPHER_MODE); SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES"); byte ivbits[] = (byte[]) ois.readObject(); IvParameterSpec iv = new IvParameterSpec(ivbits); c.init(Cipher.DECRYPT_MODE, key, iv); Mac m = Mac.getInstance("HmacSHA1"); SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1"); m.init(mackey); byte ciphertext[], cleartext[], mac[]; try { while (true) { ciphertext = (byte[]) ois.readObject(); mac = (byte[]) ois.readObject(); if (Arrays.equals(mac, m.doFinal(ciphertext))) { cleartext = c.update(ciphertext); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); } else { // System.exit(1); System.out.println(ct + "error"); } } } catch (EOFException e) { cleartext = c.doFinal(); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); System.out.println("[" + ct + "]"); } finally { if (ois != null) ois.close(); if (oos != null) oos.close(); } } catch (Exception e) { e.printStackTrace(); } }
public boolean createSelfSignedKeystore( String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null; try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
public static void testcaV3() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair keyPair = kpg.generateKeyPair(); X509Certificate cer = buildCARootCertV3(keyPair); FileUtils.writeByteArrayToFile(new File("d:\\caV3.cer"), cer.getEncoded()); System.out.println(cer); }
public void init(BigInteger p, BigInteger g) throws GeneralSecurityException { this.p = p; this.g = g; generator.initialize(new DHParameterSpec(p, g)); final KeyPair kp = generator.generateKeyPair(); agreement.init(kp.getPrivate()); e = ((javax.crypto.interfaces.DHPublicKey) kp.getPublic()).getY(); }
static { try { keyPairGenerator = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } keyPairGenerator.initialize(2048); }
private static KeyPair generateKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign"); kpg.initialize(512, new SecureRandom()); return kpg.generateKeyPair(); }