List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:org.ejbca.extra.db.KeyStoreRetrievalResponse.java
License:Open Source License
/** * Create a new message./*from w w w . j a v a 2 s . c o m*/ * * @param requestId should be the same unique identifier as in the request. * @param success true if the request was successful * @param failinfo description of the error if the request was unsuccessful * @param keyStoreType One of SecConst.TOKEN_SOFT_... * @param keyStore byte encoded keyStore object * * @see org.ejbca.extra.db.ExtRAResponse#ExtRAResponse(long, boolean, String) */ public KeyStoreRetrievalResponse(long requestId, boolean success, String failinfo, Integer keyStoreType, byte[] keyStore) { super(requestId, success, failinfo); data.put(VERSION, Float.valueOf(LATEST_VERSION)); data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(KEYSTORE_TYPE, keyStoreType); if (keyStore != null) { data.put(KEYSTORE, new String(Base64.encode(keyStore))); } else { data.put(KEYSTORE, null); } }
From source file:org.ejbca.extra.db.PKCS10Response.java
License:Open Source License
/** * Default constructor that should be used. * /*from www . ja va 2s . c o m*/ * @param requestId * @param success * @param failinfo * @param certificate the generated certificate, or null if request failed. * @param pkcs7 the generated certificate in a pkcs7 signed by the CA andincluding the certificate chain, or null if request or pkcs7 generation failed. * */ public PKCS10Response(long requestId, boolean success, String failinfo, X509Certificate certificate, byte[] pkcs7) { super(requestId, success, failinfo); try { data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(VERSION, Float.valueOf(LATEST_VERSION)); if (certificate != null) { String certstring = new String(Base64.encode(certificate.getEncoded())); data.put(CERTIFICATE, certstring); } if (pkcs7 != null) { String pkcs7str = new String(Base64.encode(pkcs7)); data.put(PKCS7, pkcs7str); } } catch (CertificateEncodingException e) { log.error("Certificate encoding failed", e); } }
From source file:org.ejbca.extra.db.PKCS12Response.java
License:Open Source License
/** * Default constructor that should be used. * //from w w w .ja v a 2 s . c o m */ public PKCS12Response(long requestId, boolean success, String failinfo, KeyStore pkcs12, String password) { super(requestId, success, failinfo); try { data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(VERSION, Float.valueOf(LATEST_VERSION)); if (pkcs12 != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); pkcs12.store(baos, password.toCharArray()); String keystorestring = new String(Base64.encode(baos.toByteArray())); baos.close(); data.put(KEYSTORE, keystorestring); } } catch (Exception e) { log.error("KeyStore encoding failed", e); } }
From source file:org.ejbca.extra.db.SubMessages.java
License:Open Source License
/** * Method used to persist the set of submessages * @return a String representation of the data *///from www . j av a2s .c om String save() { String retval = null; ArrayList savearray = new ArrayList(); Iterator<ISubMessage> iter = submessages.iterator(); while (iter.hasNext()) { ISubMessage next = iter.next(); savearray.add(next.saveData()); } try { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(savearray); byte[] messagedata = baos.toByteArray(); if (isSigned) { messagedata = ExtRAMsgHelper.signData(userKey, userCert, messagedata); } if (isEncrypted) { messagedata = ExtRAMsgHelper.encryptData(encCert, messagedata); } java.io.ByteArrayOutputStream baos2 = new java.io.ByteArrayOutputStream(); java.beans.XMLEncoder encoder = new java.beans.XMLEncoder(baos2); encoder.writeObject(Boolean.valueOf(isSigned)); encoder.writeObject(Boolean.valueOf(isEncrypted)); encoder.writeObject(new String(Base64.encode(messagedata))); encoder.close(); retval = baos2.toString("UTF8"); } catch (Exception e) { log.error("Error writing persistent SubMessages.", e); } return retval; }
From source file:org.ejbca.extra.ra.ProtocolScepHttpTest.java
License:Open Source License
private void checkScepResponse(byte[] retMsg, String senderNonce, String transId, boolean crlRep, String digestOid, boolean noca, ResponseStatus expectedResponseStatus) throws CMSException, NoSuchProviderException, NoSuchAlgorithmException, CertStoreException, InvalidKeyException, CertificateException, SignatureException, CRLException, IOException { //// w w w . j av a 2 s.co m // Parse response message // CMSSignedData s = new CMSSignedData(retMsg); // The signer, i.e. the CA, check it's the right CA SignerInformationStore signers = s.getSignerInfos(); Collection col = signers.getSigners(); assertTrue(col.size() > 0); Iterator iter = col.iterator(); SignerInformation signerInfo = (SignerInformation) iter.next(); // Check that the message is signed with the correct digest alg assertEquals(signerInfo.getDigestAlgOID(), digestOid); SignerId sinfo = signerInfo.getSID(); // Check that the signer is the expected CA assertEquals(CertTools.stringToBCDNString(racert.getIssuerDN().getName()), CertTools.stringToBCDNString(sinfo.getIssuerAsString())); // Verify the signature boolean ret = signerInfo.verify(racert.getPublicKey(), "BC"); assertTrue(ret); // Get authenticated attributes AttributeTable tab = signerInfo.getSignedAttributes(); // --Fail info Attribute attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_failInfo)); // No failInfo on this success message if (expectedResponseStatus == ResponseStatus.SUCCESS) { assertNull(attr); } // --Message type attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_messageType)); assertNotNull(attr); ASN1Set values = attr.getAttrValues(); assertEquals(values.size(), 1); DERString str = DERPrintableString.getInstance((values.getObjectAt(0))); String messageType = str.getString(); assertEquals("3", messageType); // --Success status attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_pkiStatus)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); String responsestatus = str.getString(); assertEquals(expectedResponseStatus.getValue(), responsestatus); // --SenderNonce attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_senderNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // SenderNonce is something the server came up with, but it should be 16 chars assertTrue(octstr.getOctets().length == 16); // --Recipient Nonce attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_recipientNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // recipient nonce should be the same as we sent away as sender nonce assertEquals(senderNonce, new String(Base64.encode(octstr.getOctets()))); // --Transaction ID attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_transId)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); // transid should be the same as the one we sent assertEquals(transId, str.getString()); // // Check different message types // if (!responsestatus.equals(ResponseStatus.PENDING.getValue()) && messageType.equals("3")) { // First we extract the encrypted data from the CMS enveloped data contained // within the CMS signed data CMSProcessable sp = s.getSignedContent(); byte[] content = (byte[]) sp.getContent(); CMSEnvelopedData ed = new CMSEnvelopedData(content); RecipientInformationStore recipients = ed.getRecipientInfos(); Collection c = recipients.getRecipients(); assertEquals(c.size(), 1); Iterator it = c.iterator(); byte[] decBytes = null; RecipientInformation recipient = (RecipientInformation) it.next(); decBytes = recipient.getContent(keys.getPrivate(), "BC"); // This is yet another CMS signed data CMSSignedData sd = new CMSSignedData(decBytes); // Get certificates from the signed data CertStore certstore = sd.getCertificatesAndCRLs("Collection", "BC"); if (crlRep) { // We got a reply with a requested CRL Collection crls = certstore.getCRLs(null); assertEquals(crls.size(), 1); it = crls.iterator(); X509CRL retCrl = null; // CRL is first (and only) retCrl = (X509CRL) it.next(); log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName()); // try { // FileOutputStream fos = new FileOutputStream("sceptest.der"); // fos.write(retCrl.getEncoded()); // fos.close(); // } catch (Exception e) {} // check the returned CRL assertEquals(cacert.getSubjectDN().getName(), retCrl.getIssuerDN().getName()); retCrl.verify(cacert.getPublicKey()); } else { // We got a reply with a requested certificate Collection certs = certstore.getCertificates(null); log.info("Got certificate reply with certchain of length: " + certs.size()); // EJBCA returns the issued cert and the CA cert (cisco vpn client requires that the ca cert is included) if (noca) { assertEquals(certs.size(), 1); } else { assertEquals(certs.size(), 2); } it = certs.iterator(); // Issued certificate must be first boolean verified = false; boolean gotcacert = false; String mysubjectdn = CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest"); X509Certificate usercert = null; while (it.hasNext()) { X509Certificate retcert = (X509Certificate) it.next(); // try { // FileOutputStream fos = new FileOutputStream("sceptest.der"); // fos.write(retcert.getEncoded()); // fos.close(); // } catch (Exception e) {} // check the returned certificate String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName()); if (mysubjectdn.equals(subjectdn)) { System.out.println("Got user cert with DN: " + retcert.getSubjectDN().getName()); // issued certificate assertEquals(CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest"), subjectdn); //System.out.println(retcert); //System.out.println(cacert); retcert.verify(cacert.getPublicKey()); assertTrue(checkKeys(keys.getPrivate(), retcert.getPublicKey())); verified = true; String altName = CertTools.getSubjectAlternativeName(retcert); assertEquals("iPAddress=10.0.0.1, dNSName=foo.bar.com", altName); usercert = retcert; } else { log.info("Got CA cert with DN: " + retcert.getSubjectDN().getName()); // ca certificate assertEquals(cacert.getSubjectDN().getName(), retcert.getSubjectDN().getName()); gotcacert = true; usercert.verify(retcert.getPublicKey()); } } assertTrue(verified); if (noca) { assertFalse(gotcacert); } else { assertTrue(gotcacert); } } } }
From source file:org.ejbca.extra.ra.ProtocolScepHttpTest.java
License:Open Source License
private byte[] sendScep(boolean post, byte[] scepPackage, boolean noca) throws IOException { // POST the OCSP request // we are going to do a POST String resource = resourceScep; if (noca) {//from ww w .j a va2 s .c om resource = resourceScepNoCA; } String urlString = httpReqPath + '/' + resource + "?operation=PKIOperation"; log.debug("UrlString =" + urlString); log.debug("scepPackage.length: " + scepPackage.length); HttpURLConnection con = null; if (post) { URL url = new URL(urlString); con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.connect(); // POST it OutputStream os = con.getOutputStream(); os.write(scepPackage); os.close(); } else { String reqUrl = urlString + "&message=" + URLEncoder.encode(new String(Base64.encode(scepPackage)), "UTF-8"); URL url = new URL(reqUrl); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.getDoOutput(); con.connect(); } log.debug("HTTP response message: " + con.getResponseMessage()); assertEquals("Response code ", 200, con.getResponseCode()); assertEquals("Content-Type", "application/x-pki-message", con.getContentType()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and SCEP requests are small enough InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); assertNotNull("Response can not be null.", respBytes); assertTrue(respBytes.length > 0); return respBytes; }
From source file:org.ejbca.extra.ra.ScepRequestGenerator.java
License:Open Source License
private CMSSignedData sign(CMSProcessable signThis, String messageType) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, InvalidAlgorithmParameterException, CertStoreException { CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator(); // add authenticated attributes...status, transactionId, sender- and more... Hashtable attributes = new Hashtable(); DERObjectIdentifier oid;/*from ww w.j a v a 2s.c o m*/ Attribute attr; DERSet value; // Message type (certreq) oid = new DERObjectIdentifier(ScepRequestMessage.id_messageType); value = new DERSet(new DERPrintableString(messageType)); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); // TransactionId byte[] digest = CertTools.generateMD5Fingerprint(cert.getPublicKey().getEncoded()); transactionId = new String(Base64.encode(digest)); oid = new DERObjectIdentifier(ScepRequestMessage.id_transId); value = new DERSet(new DERPrintableString(Base64.encode(digest))); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); // senderNonce byte[] nonce = new byte[16]; SecureRandom randomSource = SecureRandom.getInstance("SHA1PRNG"); randomSource.nextBytes(nonce); senderNonce = new String(Base64.encode(nonce)); if (nonce != null) { oid = new DERObjectIdentifier(ScepRequestMessage.id_senderNonce); log.debug("Added senderNonce: " + senderNonce); value = new DERSet(new DEROctetString(nonce)); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // Add our signer info and sign the message ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); gen1.addCertificatesAndCRLs(certs); gen1.addSigner(keys.getPrivate(), cert, digestOid, new AttributeTable(attributes), null); // The signed data to be enveloped CMSSignedData s = gen1.generate(signThis, true, "BC"); return s; }
From source file:org.ejbca.ra.RaCasPageBean.java
License:Open Source License
/** @return the issuer hash in base64 encoding without padding which is the way RFC4387 search function expects the iHash parameter. */ private String getSubjectPrincipalHashAsUnpaddedBase64(final X509Certificate x509Certificate) { final byte[] hashSubjectX500Principal = CertTools .generateSHA1Fingerprint(x509Certificate.getSubjectX500Principal().getEncoded()); return new String(Base64.encode(hashSubjectX500Principal)).substring(0, 27).replaceAll("\\+", "%2B"); }
From source file:org.freenetproject.freemail.smtp.SMTPAuthTest.java
License:Open Source License
/** * Checks that the server rejects the auth command after the client has already been authenticated. * @see <a href="https://tools.ietf.org/html/rfc4954#section-4">RFC4954 Section 4</a> *//*from w ww.j av a 2 s . c o m*/ @Test public void rejectsSecondAuth() throws IOException { final String authData = new String(Base64.encode(("\0" + BASE64_USERNAME + "\0password").getBytes("ASCII")), "ASCII"); List<String> commands = new LinkedList<String>(); commands.add("AUTH PLAIN " + authData); commands.add("AUTH PLAIN " + authData); List<String> expectedResponse = new LinkedList<String>(); expectedResponse.add("220 localhost ready"); expectedResponse.add("235 Authenticated"); expectedResponse.add("503 Already authenticated"); runSimpleTest(commands, expectedResponse); }
From source file:org.freenetproject.freemail.smtp.SMTPAuthTest.java
License:Open Source License
@Test public void correctAuthPlainNoInitial() throws IOException { List<String> commands = new LinkedList<String>(); commands.add("AUTH PLAIN"); final String authData = new String( Base64.encode((BASE64_USERNAME + "\0" + BASE64_USERNAME + "\0password").getBytes("ASCII")), "ASCII"); commands.add(authData);/* w w w.j av a2s .com*/ List<String> expectedResponse = new LinkedList<String>(); expectedResponse.add("220 localhost ready"); expectedResponse.add("334 "); expectedResponse.add("235 Authenticated"); runSimpleTest(commands, expectedResponse); }