List of usage examples for java.security KeyPairGenerator initialize
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException
From source file:MainClass.java
public static void main(String args[]) throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); random.setSeed(101L);/*from ww w.j a va2 s. c o m*/ keyGen.initialize(1024, random); KeyPair keypair = keyGen.generateKeyPair(); KeyFactory kfactory = KeyFactory.getInstance("DSA"); DSAPublicKeySpec kspec = (DSAPublicKeySpec) kfactory.getKeySpec(keypair.getPublic(), DSAPublicKeySpec.class); System.out.println(keypair.getPublic()); FileOutputStream fos = new FileOutputStream("publicKeys"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(kspec.getY()); oos.writeObject(kspec.getP()); oos.writeObject(kspec.getQ()); oos.writeObject(kspec.getG()); FileInputStream fin = new FileInputStream("publicKeys"); ObjectInputStream ois = new ObjectInputStream(fin); BigInteger Y = (BigInteger) ois.readObject(); BigInteger P = (BigInteger) ois.readObject(); BigInteger Q = (BigInteger) ois.readObject(); BigInteger G = (BigInteger) ois.readObject(); DSAPublicKeySpec keyspec = new DSAPublicKeySpec(Y, P, Q, G); PublicKey pkey = kfactory.generatePublic(keyspec); System.out.println(pkey); }
From source file:SignatureTest.java
public static void main(String[] args) { try {// w ww. j a va 2s .c o m if (args[0].equals("-genkeypair")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-sign")) { ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); PrivateKey privkey = (PrivateKey) keyIn.readObject(); keyIn.close(); Signature signalg = Signature.getInstance("DSA"); signalg.initSign(privkey); File infile = new File(args[1]); InputStream in = new FileInputStream(infile); int length = (int) infile.length(); byte[] message = new byte[length]; in.read(message, 0, length); in.close(); signalg.update(message); byte[] signature = signalg.sign(); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); int signlength = signature.length; out.writeInt(signlength); out.write(signature, 0, signlength); out.write(message, 0, length); out.close(); } else if (args[0].equals("-verify")) { ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[2])); PublicKey pubkey = (PublicKey) keyIn.readObject(); keyIn.close(); Signature verifyalg = Signature.getInstance("DSA"); verifyalg.initVerify(pubkey); File infile = new File(args[1]); DataInputStream in = new DataInputStream(new FileInputStream(infile)); int signlength = in.readInt(); byte[] signature = new byte[signlength]; in.read(signature, 0, signlength); int length = (int) infile.length() - signlength - 4; byte[] message = new byte[length]; in.read(message, 0, length); in.close(); verifyalg.update(message); if (!verifyalg.verify(signature)) System.out.print("not "); System.out.println("verified"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/* www. j ava 2 s . c om*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:RSATest.java
public static void main(String[] args) { try {//from w ww .ja v a 2s . c om if (args[0].equals("-genkey")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-encrypt")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); // wrap with RSA public key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key publicKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); out.writeInt(wrappedKey.length); out.write(wrappedKey); InputStream in = new FileInputStream(args[1]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } else { DataInputStream in = new DataInputStream(new FileInputStream(args[1])); int length = in.readInt(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); // unwrap with RSA private key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key privateKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(args[2]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
From source file:GenSig.java
public static void main(String[] args) { /* Generate a DSA signature */ if (args.length != 1) { System.out.println("Usage: GenSig nameOfFileToSign"); } else//from www. j a v a2 s . co m try { /* Generate a key pair */ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); /* * Create a Signature object and initialize it with the private * key */ Signature dsa = Signature.getInstance("SHA1withDSA", "SUN"); dsa.initSign(priv); /* Update and sign the data */ FileInputStream fis = new FileInputStream(args[0]); BufferedInputStream bufin = new BufferedInputStream(fis); byte[] buffer = new byte[1024]; int len; while (bufin.available() != 0) { len = bufin.read(buffer); dsa.update(buffer, 0, len); } ; bufin.close(); /* * Now that all the data to be signed has been read in, generate * a signature for it */ byte[] realSig = dsa.sign(); /* Save the signature in a file */ FileOutputStream sigfos = new FileOutputStream("sig"); sigfos.write(realSig); sigfos.close(); /* Save the public key in a file */ byte[] key = pub.getEncoded(); FileOutputStream keyfos = new FileOutputStream("suepk"); keyfos.write(key); keyfos.close(); } catch (Exception e) { System.err.println("Caught exception " + e.toString()); } }
From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java
public static void main(String args[]) throws Exception { BasicConfigurator.configure();/*from w w w . j a va 2 s. c o m*/ JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(EjbcaWS.class); factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws"); factory.setServiceName(SERVICE_NAME); EjbcaWS client = (EjbcaWS) factory.create(); Client proxy = ClientProxy.getClient(client); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); TLSClientParameters tlsClientParameters = new TLSClientParameters(); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12"); InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12"); String password = "ejbca"; keyStore.load(keyInput, password.toCharArray()); keyInput.close(); keyManagerFactory.init(keyStore, password.toCharArray()); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); tlsClientParameters.setDisableCNCheck(true); tlsClientParameters.setKeyManagers(keyManagers); X509TrustManager trustAll = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"), "changeit".toCharArray())); tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll }); //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers()); conduit.setTlsClientParameters(tlsClientParameters); System.out.println(client.getEjbcaVersion()); UserDataVOWS userData = new UserDataVOWS(); userData.setEmail("test@example.com"); userData.setUsername("test@example.com"); //userData.setPassword("test@example.com"); userData.setSubjectDN("CN=test@example.com"); userData.setSubjectAltName("rfc822Name=test@example.com"); userData.setEndEntityProfileName("test"); userData.setCaName("AdminCA1"); userData.setCertificateProfileName("ENDUSER"); userData.setStatus(EJBCAConst.STATUS_NEW); userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED); try { //client.editUser(userData); SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); SecureRandom randomSource = securityFactory.createSecureRandom(); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); keyPairGenerator.initialize(2048, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder builder = new X500PrincipalBuilder(); builder.setCommonName("john doe"); builder.setEmail("test@example.com"); PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder( X500PrincipalUtils.toX500Name(builder.buildPrincipal()), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); PKCS10CertificationRequest pkcs10 = requestBuilder .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate())); String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded()); CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10, EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE); if (certificateResponse != null && certificateResponse.getData() != null) { /* * The result is a base64 encoded certificate */ Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates( new ByteArrayInputStream(Base64.decode(certificateResponse.getData()))); if (CollectionUtils.isNotEmpty(certificates)) { for (X509Certificate certificate : certificates) { System.out.println(certificate); } } else { System.out.println("No certificates found"); } } else { System.out.println("certificateResponse is empty"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.clustercontrol.util.KeyCheck.java
/** * ????????//w w w . j av a 2s.c o m * * @param args */ public static void main(String[] args) { PrivateKey privateKey = null; PublicKey publicKey = null; /// ??????? true /// ???????? false (?) boolean flag = false; if (flag) { try { // ? privateKey = getPrivateKey( "???????privateKey.txt??"); // ? publicKey = getPublicKey("???????"); // publicKey = getPublicKey(publicKeyStr); } catch (Exception e) { System.out.println("hoge" + e.getMessage()); } } else { KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance(ALGORITHM); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); // ?? 1024 generator.initialize(1024, random); KeyPair keyPair = generator.generateKeyPair(); privateKey = keyPair.getPrivate(); publicKey = keyPair.getPublic(); } catch (NoSuchAlgorithmException ex) { System.out.println(ex.getMessage()); } } // // ? System.out.println("?"); System.out.println(byte2String(privateKey.getEncoded())); System.out.println("?"); System.out.println(byte2String(publicKey.getEncoded())); // ??????? String string = "20140701_nttdata"; byte[] src = string.getBytes(); System.out.println("??String"); System.out.println(string); System.out.println("??byte"); System.out.println(byte2String(src)); // ? try { String encStr = encrypt(string, privateKey); System.out.println("?"); System.out.println(encStr); // ? String decStr = decrypt(encStr, publicKey); System.out.println("?"); System.out.println(decStr); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:org.kse.gui.dialogs.sign.DSignJar.java
public static void main(String[] args) throws Exception { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); Security.addProvider(new BouncyCastleProvider()); java.awt.EventQueue.invokeLater(new Runnable() { @Override/*ww w. j a v a2 s . co m*/ public void run() { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyPairType.RSA.jce(), "BC"); kpg.initialize(1024, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); DSignJar dialog = new DSignJar(new JFrame(), kp.getPrivate(), KeyPairType.RSA, "signature name", null); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } @Override public void windowDeactivated(WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { // Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDH", "BC"); EllipticCurve curve = new EllipticCurve( new ECFieldFp(new BigInteger("fffffffffffffffffffffffffffffffeffffffffffffffff", 16)), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16)); ECParameterSpec ecSpec = new ECParameterSpec(curve, new ECPoint(new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16)), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), 1); keyGen.initialize(ecSpec, new SecureRandom()); KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH", "BC"); KeyPair aPair = keyGen.generateKeyPair(); KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDH", "BC"); KeyPair bPair = keyGen.generateKeyPair(); aKeyAgree.init(aPair.getPrivate());/* www .j a v a 2s. com*/ bKeyAgree.init(bPair.getPrivate()); aKeyAgree.doPhase(bPair.getPublic(), true); bKeyAgree.doPhase(aPair.getPublic(), true); MessageDigest hash = MessageDigest.getInstance("SHA1", "BC"); System.out.println(new String(hash.digest(aKeyAgree.generateSecret()))); System.out.println(new String(hash.digest(bKeyAgree.generateSecret()))); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDH", "BC"); EllipticCurve curve = new EllipticCurve( new ECFieldFp(new BigInteger("fffffffffffffffffffffffffffffffeffffffffffffffff", 16)), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16)); ECParameterSpec ecSpec = new ECParameterSpec(curve, new ECPoint(new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16)), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), 1); keyGen.initialize(ecSpec, new SecureRandom()); KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH", "BC"); KeyPair aPair = keyGen.generateKeyPair(); KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDH", "BC"); KeyPair bPair = keyGen.generateKeyPair(); aKeyAgree.init(aPair.getPrivate());//from w w w. ja v a 2s .c om bKeyAgree.init(bPair.getPrivate()); aKeyAgree.doPhase(bPair.getPublic(), true); bKeyAgree.doPhase(aPair.getPublic(), true); MessageDigest hash = MessageDigest.getInstance("SHA1", "BC"); System.out.println(new String(hash.digest(aKeyAgree.generateSecret()))); System.out.println(new String(hash.digest(bKeyAgree.generateSecret()))); }