List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.dasein.cloud.google.compute.server.ServerSupport.java
private JSONObject jsonEncode(KeyPair keys) throws InternalException { JSONObject returnJson = new JSONObject(); try {//from w ww .j a v a2s . c om KeyFactory factory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), RSAPublicKeySpec.class); BigInteger modulus = pubSpec.getModulus(); BigInteger exponent = pubSpec.getPublicExponent(); BaseEncoding stringEncoder = BaseEncoding.base64(); // Strip out the leading 0 byte in the modulus. byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length); returnJson.put("modulus", stringEncoder.encode(arr).replaceAll("\n", "")); returnJson.put("exponent", stringEncoder.encode(exponent.toByteArray()).replaceAll("\n", "")); } catch (Exception e) { throw new InternalException(e); } return returnJson; }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
@Test public void test06NotNestedMessage() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { ASN1EncodableVector optionaValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionaValidityV.add(new DERTaggedObject(true, 0, nb)); optionaValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionaValidityV)); KeyPair keys = KeyTools.genKeys("1024", "RSA"); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); myCertTemplate.setIssuer(new X500Name(this.issuerDN)); myCertTemplate.setSubject(SUBJECT_DN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try {/*from www. j a v a2 s . c om*/ SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); // If we did not pass any extensions as parameter, we will create some of our own, standard ones } finally { dIn.close(); } final Extensions exts; { // SubjectAltName ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); // KeyUsage int bcku = 0; bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation; X509KeyUsage ku = new X509KeyUsage(bcku); bOut = new ByteArrayOutputStream(); dOut = new DEROutputStream(bOut); dOut.writeObject(ku); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value)); // Make the complete extension package exts = extgen.generate(); } myCertTemplate.setExtensions(exts); CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); ProofOfPossession myProofOfPossession = new ProofOfPossession(); AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("foo123")); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(SUBJECT_DN), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); PKIBody myPKIBody = new PKIBody(20, myCertReqMessages); // nestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raSignerTest06", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create PKIHeader", myPKIHeader); assertNotNull("Failed to create PKIBody", myPKIBody); assertNotNull("Failed to create PKIMessage", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("unknown object in getInstance: org.bouncycastle.asn1.DERSequence", errMsg); }
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair) throws Exception { SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo(); RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo); RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent()); KeyFactory kf = KeyFactory.getInstance(ALG_RSA); PublicKey publicKey = kf.generatePublic(rsaSpec); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - DateConstant.ONE_DAY), new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo); ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER) .build(pKeyPair.getPrivate()); X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER) .getCertificate(certBuilder.build(signer)); signedCert.verify(pKeyPair.getPublic()); return signedCert; }
From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java
private X509Certificate generateV3Certificate(KeyPair pair, String certSubjectDN, Calendar before, Calendar expiry) throws CryptoException { X509V3CertificateGenerator cert = new X509V3CertificateGenerator(); /* Set the certificate serial number to a random number */ Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); /* Generates a number between 0 and 2^32 as the serial */ BigInteger serial = BigInteger.valueOf(rand.nextInt(Integer.MAX_VALUE)); logger.info("Setting X509 Cert Serial to: " + serial); cert.setSerialNumber(serial);//from w w w .j ava 2 s .c om /* Set the certificate issuer */ cert.setIssuerDN(new X500Principal(this.certIssuerDN)); /* Set the start of valid period. */ cert.setNotBefore(before.getTime()); /* Set the certificate expiry date. */ cert.setNotAfter(expiry.getTime()); /* Set the subject */ cert.setSubjectDN(new X500Principal(certSubjectDN)); cert.setPublicKey(pair.getPublic()); /* Signature algorithm, this may need to be changed if not all hosts have SHA256 and RSA implementations */ cert.setSignatureAlgorithm("SHA512withRSA"); cert.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); /* Only for signing */ cert.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign)); cert.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); /* Set a contact email address for the issuer */ cert.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, this.certIssuerEmail))); logger.debug("Generating X509Certificate for key pair: " + pair); try { /* Use the BouncyCastle provider to actually generate the X509Certificate now */ return cert.generateX509Certificate(pair.getPrivate(), "BC"); } catch (InvalidKeyException e) { this.logger.error("InvalidKeyException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (NoSuchProviderException e) { this.logger.error("NoSuchProviderException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (SecurityException e) { this.logger.error("SecurityException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (SignatureException e) { this.logger.error("SignatureException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } }
From source file:duthientan.mmanm.com.Main.java
private void BntGenerationKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntGenerationKeyActionPerformed // TODO add your handling code here: if (filePath.size() != 0) { progressBarCipher.setIndeterminate(true); new Thread(new Runnable() { @Override//from w w w. j av a2 s . c o m public void run() { try { Path path = Paths.get(filePath.get(0)); String srcParent = path.getParent().toString(); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); final KeyPair key = keyGen.generateKeyPair(); File privateKeyFile = new File(srcParent + "/private.key"); File publicKeyFile = new File(srcParent + "/public.key"); publicKeyFile.createNewFile(); publicKeyFile.createNewFile(); ObjectOutputStream publicKeyOS = new ObjectOutputStream( new FileOutputStream(publicKeyFile)); publicKeyOS.writeObject(key.getPublic()); publicKeyOS.close(); ObjectOutputStream privateKeyOS = new ObjectOutputStream( new FileOutputStream(privateKeyFile)); privateKeyOS.writeObject(key.getPrivate()); privateKeyOS.close(); progressBarCipher.setIndeterminate(false); JFrame frame = new JFrame("COMPLETED"); JOptionPane.showMessageDialog(frame, "Greneration Key File Completed"); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } else { JFrame frame = new JFrame("ERROR"); JOptionPane.showMessageDialog(frame, "Please Choice File To Cipher Before Greneration Key"); } }
From source file:mitm.common.security.ca.SMIMEKeyAndCertificateIssuer.java
@Override public KeyAndCertificate issueKeyAndCertificate(RequestParameters parameters, KeyAndCertificate signer) throws CAException { try {//from w w w .j av a 2s . c om if (StringUtils.isBlank(parameters.getEmail())) { throw new CAException("email must be specified."); } if (parameters.getSubject() == null) { throw new CAException("subject must be specified."); } if (signer == null || signer.getCertificate() == null || signer.getPrivateKey() == null) { throw new CAException("issuer fields must be non-null."); } KeyPair keyPair = generateKeyPair(parameters); Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>(); keyUsage.add(KeyUsageType.DIGITALSIGNATURE); keyUsage.add(KeyUsageType.KEYENCIPHERMENT); Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); SerialNumberGenerator serialNumberGenerator = new StandardSerialNumberGenerator(); BigInteger serialNumber = serialNumberGenerator.generate(); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names(parameters.getEmail()); X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); Date now = new Date(); certificateBuilder.setAltNames(altNamesBuider.buildAltNames(), false); certificateBuilder.setSubject(parameters.getSubject()); certificateBuilder.setIssuer(signer.getCertificate().getSubjectX500Principal()); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false); certificateBuilder.setNotBefore(DateUtils.addDays(now, -1)); certificateBuilder.setNotAfter(DateUtils.addDays(now, parameters.getValidity())); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm(parameters.getSignatureAlgorithm()); certificateBuilder.addSubjectKeyIdentifier(true); if (StringUtils.isNotBlank(parameters.getCRLDistributionPoint())) { certificateBuilder .setCRLDistributionPoints(Collections.singleton(parameters.getCRLDistributionPoint())); } X509Certificate certificate = certificateBuilder.generateCertificate(signer.getPrivateKey(), signer.getCertificate()); return new KeyAndCertificateImpl(keyPair.getPrivate(), certificate); } catch (NoSuchAlgorithmException e) { throw new CAException(e); } catch (NoSuchProviderException e) { throw new CAException(e); } catch (CertificateBuilderException e) { throw new CAException(e); } catch (IllegalStateException e) { throw new CAException(e); } catch (IOException e) { throw new CAException(e); } }
From source file:mitm.common.security.certificate.GenerateBulkPFX.java
private void generateCertificate(String email, String commonName, String alias) throws Exception { X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder(); subjectBuilder.setCommonName(commonName); subjectBuilder.setEmail(email);//from www. j a v a2 s .c o m subjectBuilder.setCountryCode("NL"); subjectBuilder.setLocality("Amsterdam"); subjectBuilder.setState("NH"); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names(email); X500Principal subject = subjectBuilder.buildPrincipal(); GeneralNames altNames = altNamesBuider.buildAltNames(); Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>(); keyUsage.add(KeyUsageType.DIGITALSIGNATURE); keyUsage.add(KeyUsageType.KEYENCIPHERMENT); keyUsage.add(KeyUsageType.NONREPUDIATION); Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); BigInteger serialNumber = serialNumberGenerator.generate(); Date now = new Date(); certificateBuilder.setSubject(subject); certificateBuilder.setAltNames(altNames, true); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false); certificateBuilder.setNotBefore(now); certificateBuilder.setNotAfter(DateUtils.addYears(now, 20)); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption"); certificateBuilder.addSubjectKeyIdentifier(true); X509Certificate certificate = certificateBuilder.generateCertificate(caPrivateKey, caCertificate); assertNotNull(certificate); Certificate[] chain = new Certificate[] { certificate, caCertificate, rootCertificate }; keyStore.setKeyEntry(alias, keyPair.getPrivate(), null, chain); }
From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java
/** * Tests that the provided cardnumber is stored in the EndEntityInformation * and that when querying for EndEntityInformation the cardnumber is * returned.//from w ww .ja v a 2 s .c o m * @throws Exception in case of error */ @Test public void test48CertificateRequestWithCardNumber() throws Exception { String userName = "wsRequestCardNumber" + new SecureRandom().nextLong(); // Generate a CSR KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(), keys.getPrivate(), null); final String csr = new String(Base64.encode(pkcs10.toASN1Structure().getEncoded())); // Set some user data final UserDataVOWS userData = new UserDataVOWS(); userData.setUsername(userName); userData.setPassword(PASSWORD); userData.setClearPwd(true); userData.setSubjectDN("CN=test" + secureRandom.nextLong() + ", UID=" + userName + ", O=Test, C=SE"); userData.setCaName(getAdminCAName()); userData.setEmail(null); userData.setSubjectAltName(null); userData.setStatus(UserDataVOWS.STATUS_NEW); userData.setTokenType(UserDataVOWS.TOKEN_TYPE_P12); userData.setEndEntityProfileName("EMPTY"); userData.setCertificateProfileName("ENDUSER"); // Set the card number userData.setCardNumber("1234fa"); // Issue a certificate CertificateResponse response = ejbcaraws.certificateRequest(userData, csr, CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull("null response", response); // Check that the cardnumber was stored in the EndEntityInformation EndEntityInformation endEntity = endEntityAccessSession.findUser(intAdmin, userName); assertEquals("stored cardnumber ejb", "1234fa", endEntity.getCardNumber()); // Check that the cardnumber is also available when querying using WS UserMatch criteria = new UserMatch(); criteria.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); criteria.setMatchwith(UserMatch.MATCH_WITH_USERNAME); criteria.setMatchvalue(userName); UserDataVOWS user = ejbcaraws.findUser(criteria).get(0); assertEquals("stored cardnumber ws", "1234fa", user.getCardNumber()); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys, Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions, Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, InvalidKeyException, SignatureException { ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); if (notBefore != null) { nb = new org.bouncycastle.asn1.x509.Time(notBefore); }//from ww w . ja v a2s . c o m optionalValidityV.add(new DERTaggedObject(true, 0, nb)); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); if (notAfter != null) { na = new org.bouncycastle.asn1.x509.Time(notAfter); } optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); if (issuerDN != null) { myCertTemplate.setIssuer(new X500Name(issuerDN)); } myCertTemplate.setSubject(userDN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); dIn.close(); myCertTemplate.setPublicKey(keyInfo); // If we did not pass any extensions as parameter, we will create some of our own, standard ones Extensions exts = extensions; if (exts == null) { // SubjectAltName // Some altNames ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dOut = new ASN1OutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); if (altNames != null) { GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames); dOut.writeObject(san); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.subjectAlternativeName, false, value); } // KeyUsage int bcku = 0; bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation; KeyUsage ku = new KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku)); // Make the complete extension package exts = extgen.generate(); } myCertTemplate.setExtensions(exts); if (customCertSerno != null) { // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order // to request a custom certificate serial number (something not standard anyway) myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno)); } CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (raVerifiedPopo) { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg, "BC"); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("foo123")); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName( new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(pAlg); myPKIHeader.setSenderKID(senderKID); PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization // request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:com.trsst.client.Client.java
/** * Posts a new entry to the feed associated with the specified public * signing key to the home server, creating a new feed if needed. * /*from w w w .j a v a2 s. c o m*/ * @param signingKeys * Required: the signing keys associated with public feed id of * this feed. * @param encryptionKey * Required: the public encryption key associated with this * account; this public key will be used by others to encrypt * private message for this account. * @param options * The data to be posted. * @return The feed as posted to the home server. * @throws IOException * @throws SecurityException * @throws GeneralSecurityException * @throws contentKey */ public Feed post(KeyPair signingKeys, KeyPair encryptionKeys, EntryOptions options, FeedOptions feedOptions) throws IOException, SecurityException, GeneralSecurityException, Exception { // inlining all the steps to help implementors and porters (and // debuggers) // configure for signing Element signedNode, signatureElement, keyInfo; AbderaSecurity security = new AbderaSecurity(Abdera.getInstance()); Signature signer = security.getSignature(); String feedId = Common.toFeedId(signingKeys.getPublic()); Feed feed = pull(feedId); if (feed == null) { feed = Abdera.getInstance().newFeed(); feed.declareNS(Common.NS_URI, Common.NS_ABBR); } // remove each entry and retain the most recent one (if any) List<Entry> entries = feed.getEntries(); Entry mostRecentEntry = null; for (Entry entry : entries) { if (mostRecentEntry == null || mostRecentEntry.getUpdated() == null || mostRecentEntry.getUpdated().before(entry.getUpdated())) { mostRecentEntry = entry; } entry.discard(); } // update and sign feed (without any entries) feed.setUpdated(new Date()); // ensure the correct keys are in place signatureElement = feed.getFirstChild(new QName(Common.NS_URI, Common.SIGN)); if (signatureElement != null) { signatureElement.discard(); } feed.addExtension(new QName(Common.NS_URI, Common.SIGN)) .setText(Common.toX509FromPublicKey(signingKeys.getPublic())); signatureElement = feed.getFirstChild(new QName(Common.NS_URI, Common.ENCRYPT)); if (signatureElement != null) { signatureElement.discard(); } feed.addExtension(new QName(Common.NS_URI, Common.ENCRYPT)) .setText(Common.toX509FromPublicKey(encryptionKeys.getPublic())); feed.setId(Common.toFeedUrn(feedId)); feed.setMustPreserveWhitespace(false); // update feed properties if (feedOptions.title != null) { feed.setTitle(feedOptions.title); } if (feedOptions.subtitle != null) { feed.setSubtitle(feedOptions.subtitle); } if (feedOptions.icon != null) { while (feed.getIconElement() != null) { feed.getIconElement().discard(); } feed.setIcon(feedOptions.icon); } if (feedOptions.logo != null) { while (feed.getLogoElement() != null) { feed.getLogoElement().discard(); } feed.setLogo(feedOptions.logo); } Person author = feed.getAuthor(); if (author == null) { // author is a required element author = Abdera.getInstance().getFactory().newAuthor(); String defaultName = feed.getTitle(); if (defaultName == null) { defaultName = Common.toFeedIdString(feed.getId()); } author.setName(defaultName); feed.addAuthor(author); } // update author if (feedOptions.name != null || feedOptions.email != null || feedOptions.uri != null) { if (feedOptions.name != null) { author.setName(feedOptions.name); } if (feedOptions.email != null) { author.setEmail(feedOptions.email); } if (feedOptions.uri != null) { if (feedOptions.uri.indexOf(':') == -1) { // default to "acct:" urn author.setUri("acct:" + feedOptions.uri + ".trsst.com"); // FIXME: domain should be specified by user } else { author.setUri(feedOptions.uri); } } } // set base if (feedOptions.base != null) { String uri = feedOptions.base; if (!uri.endsWith("/")) { uri = uri + '/'; } uri = uri + feedId; feed.setBaseUri(uri); } // set link self IRI base = feed.getBaseUri(); if (base != null) { while (feed.getLink(Link.REL_SELF) != null) { feed.getLink(Link.REL_SELF).discard(); } feed.addLink(base.toString(), Link.REL_SELF); } // holds any attachments (can be used for logo and icons) String[] contentIds = new String[options.getContentCount()]; // subject or verb or attachment is required to create an entry Entry entry = null; if (options.status != null || options.verb != null || contentIds.length > 0) { // create the new entry entry = Abdera.getInstance().newEntry(); entry.setUpdated(feed.getUpdated()); entry.setId(Common.toEntryUrn(feedId, feed.getUpdated().getTime())); entry.addLink(feedId + '/' + Common.toEntryIdString(entry.getId())); if (options.publish != null) { entry.setPublished(options.publish); } else { entry.setPublished(entry.getUpdated()); } if (options.status != null) { entry.setTitle(options.status); } else { // title is a required element: // default to verb if (options.verb != null) { entry.setTitle(options.verb); } else { // "post" is the default verb entry.setSummary("post"); } } if (options.verb != null) { feed.declareNS("http://activitystrea.ms/spec/1.0/", "activity"); entry.addSimpleExtension(new QName("http://activitystrea.ms/spec/1.0/", "verb", "activity"), options.verb); } if (options.body != null) { // was: entry.setSummary(options.body); entry.setSummary(options.body, org.apache.abdera.model.Text.Type.HTML); // FIXME: some readers only show type=html } else { // summary is a required element in some cases entry.setSummary("", org.apache.abdera.model.Text.Type.TEXT); // FIXME: use tika to generate a summary } // generate proof-of-work stamp for this feed id and entry id Element stampElement = entry.addExtension(new QName(Common.NS_URI, Common.STAMP)); stampElement.setText(Crypto.computeStamp(Common.STAMP_BITS, entry.getUpdated().getTime(), feedId)); if (options.mentions != null) { HashSet<String> set = new HashSet<String>(); for (String s : options.mentions) { if (!set.contains(s)) { set.add(s); // prevent duplicates entry.addCategory(Common.MENTION_URN, s, "Mention"); stampElement = entry.addExtension(new QName(Common.NS_URI, Common.STAMP)); stampElement .setText(Crypto.computeStamp(Common.STAMP_BITS, entry.getUpdated().getTime(), s)); // stamp is required for each mention } } } if (options.tags != null) { HashSet<String> set = new HashSet<String>(); for (String s : options.tags) { if (!set.contains(s)) { set.add(s); // prevent duplicates entry.addCategory(Common.TAG_URN, s, "Tag"); stampElement = entry.addExtension(new QName(Common.NS_URI, Common.STAMP)); stampElement .setText(Crypto.computeStamp(Common.STAMP_BITS, entry.getUpdated().getTime(), s)); // stamp is required for each tag } } } // generate an AES256 key for encrypting byte[] contentKey = null; if (options.recipientIds != null) { contentKey = Crypto.generateAESKey(); } // for each content part for (int part = 0; part < contentIds.length; part++) { byte[] currentContent = options.getContentData()[part]; String currentType = options.getMimetypes()[part]; // encrypt before hashing if necessary if (contentKey != null) { currentContent = Crypto.encryptAES(currentContent, contentKey); } // calculate digest to determine content id byte[] digest = Common.ripemd160(currentContent); contentIds[part] = new Base64(0, null, true).encodeToString(digest); // add mime-type hint to content id (if not encrypted): // (some readers like to see a file extension on enclosures) if (currentType != null && contentKey == null) { String extension = ""; int i = currentType.lastIndexOf('/'); if (i != -1) { extension = '.' + currentType.substring(i + 1); } contentIds[part] = contentIds[part] + extension; } // set the content element if (entry.getContentSrc() == null) { // only point to the first attachment if multiple entry.setContent(new IRI(contentIds[part]), currentType); } // use a base uri so src attribute is simpler to process entry.getContentElement().setBaseUri(Common.toEntryIdString(entry.getId()) + '/'); entry.getContentElement().setAttributeValue(new QName(Common.NS_URI, "hash", "trsst"), "ripemd160"); // if not encrypted if (contentKey == null) { // add an enclosure link entry.addLink(Common.toEntryIdString(entry.getId()) + '/' + contentIds[part], Link.REL_ENCLOSURE, currentType, null, null, currentContent.length); } } if (contentIds.length == 0 && options.url != null) { Content content = Abdera.getInstance().getFactory().newContent(); if (options.url.startsWith("urn:feed:") || options.url.startsWith("urn:entry:")) { content.setMimeType("application/atom+xml"); } else { content.setMimeType("text/html"); } content.setSrc(options.url); entry.setContentElement(content); } // add the previous entry's signature value String predecessor = null; if (mostRecentEntry != null) { signatureElement = mostRecentEntry .getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature")); if (signatureElement != null) { signatureElement = signatureElement .getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "SignatureValue")); if (signatureElement != null) { predecessor = signatureElement.getText(); signatureElement = entry.addExtension(new QName(Common.NS_URI, Common.PREDECESSOR)); signatureElement.setText(predecessor); signatureElement.setAttributeValue(Common.PREDECESSOR_ID, mostRecentEntry.getId().toString()); } else { log.error("No signature value found for entry: " + entry.getId()); } } else { log.error("No signature found for entry: " + entry.getId()); } } if (options.recipientIds == null) { // public post entry.setRights(Common.RIGHTS_NDBY_REVOCABLE); } else { // private post entry.setRights(Common.RIGHTS_RESERVED); try { StringWriter stringWriter = new StringWriter(); StreamWriter writer = Abdera.getInstance().getWriterFactory().newStreamWriter(); writer.setWriter(stringWriter); writer.startEntry(); writer.writeId(entry.getId()); writer.writeUpdated(entry.getUpdated()); writer.writePublished(entry.getPublished()); if (predecessor != null) { writer.startElement(Common.PREDECESSOR, Common.NS_URI); writer.writeElementText(predecessor); writer.endElement(); } if (options.publicOptions != null) { // these are options that will be publicly visible if (options.publicOptions.status != null) { writer.writeTitle(options.publicOptions.status); } else { writer.writeTitle(""); // empty title } if (options.publicOptions.body != null) { writer.writeSummary(options.publicOptions.body); } if (options.publicOptions.verb != null) { writer.startElement("verb", "http://activitystrea.ms/spec/1.0/"); writer.writeElementText(options.publicOptions.verb); writer.endElement(); } if (options.publicOptions.tags != null) { for (String s : options.publicOptions.tags) { writer.writeCategory(s); } } if (options.publicOptions.mentions != null) { for (String s : options.publicOptions.mentions) { writer.startElement("mention", Common.NS_URI, "trsst"); writer.writeElementText(s); writer.endElement(); } } } else { writer.writeTitle(""); // empty title } writer.startContent("application/xenc+xml"); List<PublicKey> keys = new LinkedList<PublicKey>(); for (String id : options.recipientIds) { // for each recipient Feed recipientFeed = pull(id); if (recipientFeed != null) { // fetch encryption key Element e = recipientFeed.getExtension(new QName(Common.NS_URI, Common.ENCRYPT)); if (e == null) { // fall back to signing key e = recipientFeed.getExtension(new QName(Common.NS_URI, Common.SIGN)); } keys.add(Common.toPublicKeyFromX509(e.getText())); } } // enforce the convention: keys.remove(encryptionKeys.getPublic()); // move to end if exists; // last encrypted key is for ourself keys.add(encryptionKeys.getPublic()); // encrypt content key separately for each recipient for (PublicKey recipient : keys) { byte[] bytes = Crypto.encryptKeyWithIES(contentKey, feed.getUpdated().getTime(), recipient, encryptionKeys.getPrivate()); String encoded = new Base64(0, null, true).encodeToString(bytes); writer.startElement("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"); writer.startElement("CipherData", "http://www.w3.org/2001/04/xmlenc#"); writer.startElement("CipherValue", "http://www.w3.org/2001/04/xmlenc#"); writer.writeElementText(encoded); writer.endElement(); writer.endElement(); writer.endElement(); } // now: encrypt the payload with content key byte[] bytes = encryptElementAES(entry, contentKey); String encoded = new Base64(0, null, true).encodeToString(bytes); writer.startElement("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"); writer.startElement("CipherData", "http://www.w3.org/2001/04/xmlenc#"); writer.startElement("CipherValue", "http://www.w3.org/2001/04/xmlenc#"); writer.writeElementText(encoded); writer.endElement(); writer.endElement(); writer.endElement(); // done with encrypted elements writer.endContent(); writer.endEntry(); writer.flush(); // this constructed entry now replaces the encrypted // entry entry = (Entry) Abdera.getInstance().getParserFactory().getParser() .parse(new StringReader(stringWriter.toString())).getRoot(); // System.out.println(stringWriter.toString()); } catch (Throwable t) { log.error("Unexpected error while encrypting, exiting: " + options.recipientIds, t); t.printStackTrace(); throw new IllegalArgumentException("Unexpected error: " + t); } } // sign the new entry signedNode = signer.sign(entry, getSignatureOptions(signer, signingKeys)); signatureElement = signedNode .getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature")); keyInfo = signatureElement.getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "KeyInfo")); if (keyInfo != null) { // remove key info (because we're not using certs) keyInfo.discard(); } entry.addExtension(signatureElement); } else { log.info("No valid entries detected; updating feed."); } // remove existing feed signature element if any signatureElement = feed.getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature")); if (signatureElement != null) { signatureElement.discard(); } // remove all navigation links before signing for (Link link : feed.getLinks()) { if (Link.REL_FIRST.equals(link.getRel()) || Link.REL_LAST.equals(link.getRel()) || Link.REL_CURRENT.equals(link.getRel()) || Link.REL_NEXT.equals(link.getRel()) || Link.REL_PREVIOUS.equals(link.getRel())) { link.discard(); } } // remove all opensearch elements before signing for (Element e : feed.getExtensions("http://a9.com/-/spec/opensearch/1.1/")) { e.discard(); } // set logo and/or icon if (contentIds.length > 0) { String url = Common.toEntryIdString(entry.getId()) + '/' + contentIds[0]; if (feedOptions.asIcon) { feed.setIcon(url); } if (feedOptions.asLogo) { feed.setLogo(url); } } // sign the feed signedNode = signer.sign(feed, getSignatureOptions(signer, signingKeys)); signatureElement = signedNode.getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature")); keyInfo = signatureElement.getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "KeyInfo")); if (keyInfo != null) { // remove key info (because we're not using certs) keyInfo.discard(); } feed.addExtension(signatureElement); // add the new entry to the feed, if there is one, // only after we have signed the feed if (entry != null) { feed.addEntry(entry); } // post to server if (contentIds.length > 0) { return push(feed, contentIds, options.getMimetypes(), options.getContentData(), serving); } return push(feed, serving); }