List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:org.dasein.security.joyent.SignatureHttpAuth.java
License:Apache License
@Override public void addPreemptiveAuth(@Nonnull HttpRequest request) throws CloudException, InternalException { if (provider.getContext() == null) { throw new CloudException("No context was defined for this request"); }// w w w .j a va 2 s. c o m Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime(); String now = RFC1123_DATE_FORMAT.format(date); request.setHeader("Date", now); try { Security.addProvider(new BouncyCastleProvider()); Signature signature = Signature.getInstance(SIGN_ALGORITHM); List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues(); String keyName = ""; String privateKey = ""; char[] keyPassword = null; for (ContextRequirements.Field f : fields) { if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) { byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f); keyName = new String(keyPair[0], "utf-8"); privateKey = new String(keyPair[1], "utf-8"); } else if (f.type.equals(ContextRequirements.FieldType.PASSWORD)) { byte[] password = (byte[]) provider.getContext().getConfigurationValue(f); if (password != null) { keyPassword = new String(password, "utf-8").toCharArray(); } } } signature.initSign(getKeyPair(privateKey, keyPassword).getPrivate()); String signingString = String.format(AUTH_SIGN, now); signature.update(signingString.getBytes("UTF-8")); byte[] signedDate = signature.sign(); byte[] encodedSignedDate = Base64.encode(signedDate); request.addHeader("Authorization", String.format(AUTH_HEADER, provider.getContext().getAccountNumber(), keyName, new String(encodedSignedDate))); } catch (NoSuchAlgorithmException e) { throw new InternalException(e); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } catch (SignatureException e) { throw new InternalException(e); } catch (InvalidKeyException e) { throw new InternalException(e); } catch (IOException e) { throw new InternalException(e); } }
From source file:org.debux.webmotion.server.BouncyCastleTest.java
License:Open Source License
@Test public void testEncryptRijndael() throws DataLengthException, IllegalStateException, InvalidCipherTextException { BlockCipher engine = new RijndaelEngine(256); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding()); byte[] keyBytes = "0123456789abcdef0123456789abcdef".getBytes(); cipher.init(true, new KeyParameter(keyBytes)); byte[] input = "value".getBytes(); byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0); cipher.doFinal(cipherText, cipherLength); String result = new String(Base64.encode(cipherText)); log.debug("result : " + result); AssertJUnit.assertNotNull(result);/*w ww . j a v a 2 s . com*/ }
From source file:org.debux.webmotion.server.BouncyCastleTest.java
License:Open Source License
@Test public void testSha1() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] keyBytes = "0123456789abcdef0123456789abcdef".getBytes(); SecretKey secretKey = new SecretKeySpec(keyBytes, "HMac-SHA1"); Mac mac = Mac.getInstance("HMac-SHA1", "BC"); mac.init(secretKey);/* www .ja v a2 s.com*/ mac.reset(); byte[] input = "value".getBytes(); mac.update(input, 0, input.length); byte[] out = mac.doFinal(); String result = new String(Base64.encode(out)); log.debug("result : " + result); AssertJUnit.assertNotNull(result); }
From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java
License:Open Source License
/** * This method sends a keypair off to be signed by the CA that issued the original keychain. * // ww w.j av a 2s. com * @return a certificate that has been signed by the CA. * @throws KeyRenewalFailedException if any error occurs during signing * @throws CryptoTokenOfflineException */ @SuppressWarnings("unchecked") private X509Certificate signCertificateByCa(EjbcaWS ejbcaWS, OcspSigningCacheEntry ocspSigningCacheEntry) throws KeyRenewalFailedException, CryptoTokenOfflineException { /* Construct a certification request in order to have the new keystore certified by the CA. */ //final int caId = CertTools.stringToBCDNString(tokenAndChain.getCaCertificate().getSubjectDN().toString()).hashCode(); final int caId = CertTools.getSubjectDN(ocspSigningCacheEntry.getCaCertificateChain().get(0)).hashCode(); final X509Certificate ocspSigningCertificate = ocspSigningCacheEntry.getOcspSigningCertificate(); final UserDataVOWS userData = getUserDataVOWS(ejbcaWS, ocspSigningCertificate, caId); if (userData == null) { final String msg = "User data for certificate with subject DN '" + CertTools.getSubjectDN(ocspSigningCertificate) + "' was not found."; log.error(msg); throw new KeyRenewalFailedException(msg); } editUser(ejbcaWS, userData); final int internalKeyBindingId = ocspSigningCacheEntry.getOcspKeyBinding().getId(); final byte[] pkcs10CertificationRequest; try { pkcs10CertificationRequest = internalKeyBindingMgmtSession.generateCsrForNextKey(authenticationToken, internalKeyBindingId); } catch (AuthorizationDeniedException e) { throw new KeyRenewalFailedException(e); } CertificateResponse certificateResponse; try { certificateResponse = ejbcaWS.pkcs10Request(userData.getUsername(), userData.getPassword(), new String(Base64.encode(pkcs10CertificationRequest)), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); } catch (Exception e) { //Way too many silly exceptions to handle, wrap instead. throw new KeyRenewalFailedException(e); } if (certificateResponse == null) { throw new KeyRenewalFailedException("Certificate Response was not received"); } Collection<X509Certificate> certificates; try { certificates = (Collection<X509Certificate>) CertificateFactory.getInstance("X.509") .generateCertificates(new ByteArrayInputStream(Base64.decode(certificateResponse.getData()))); } catch (CertificateException e) { throw new KeyRenewalFailedException(e); } final byte[] publicKeyBytes; try { publicKeyBytes = internalKeyBindingMgmtSession .getNextPublicKeyForInternalKeyBinding(authenticationToken, internalKeyBindingId); } catch (AuthorizationDeniedException e) { throw new KeyRenewalFailedException(e); } if (log.isDebugEnabled()) { log.debug("Number of certificates returned from WS: " + certificates.size()); } X509Certificate signedCertificate = null; final X509Certificate caCertificate = ocspSigningCacheEntry.getCaCertificateChain().get(0); final PublicKey caCertificatePublicKey = caCertificate.getPublicKey(); for (X509Certificate certificate : certificates) { if (log.isDebugEnabled()) { log.debug("Verifying certificate with SubjectDN : '" + CertTools.getSubjectDN(certificate) + "' using public key from CA certificate with subject '" + CertTools.getSubjectDN(caCertificate) + "'."); } try { certificate.verify(caCertificatePublicKey); } catch (Exception e) { //Ugly, but inherited from legacy code signedCertificate = null; log.error("Exception was caught when verifying certificate", e); continue; } // Comparing public keys is dependent on provider used, so we must ensure same provider is used for the public keys // Otherwise this will fail, even though it should work // Both certPublicKey and nextPublicKey is obtained using KeyTools.getPublicKeyFromBytes, which uses the BC provider final PublicKey certPublicKey = KeyTools.getPublicKeyFromBytes(certificate.getPublicKey().getEncoded()); final PublicKey nextPublicKey = KeyTools.getPublicKeyFromBytes(publicKeyBytes); if (nextPublicKey.equals(certPublicKey)) { signedCertificate = certificate; break; } else if (log.isDebugEnabled()) { log.debug("Matching public keys failed: "); log.debug("Certificate public key: " + certificate.getPublicKey()); log.debug("Next public key: " + nextPublicKey); } } if (signedCertificate == null) { throw new KeyRenewalFailedException("No certificate signed by correct CA generated."); } return signedCertificate; }
From source file:org.ejbca.core.protocol.certificatestore.HashID.java
License:Open Source License
private HashID(byte hash[]) { final String b64padded = new String(Base64.encode(hash)); if (b64padded.length() != 28 || b64padded.charAt(27) != '=') { this.isOK = false; this.b64 = b64padded; } else {/*from ww w. j a v a2s . com*/ this.isOK = true; this.b64 = b64padded.substring(0, 27); } this.b64url = this.b64.replaceAll("\\+", "%2B"); this.key = new Integer(new BigInteger(hash).hashCode()); }
From source file:org.ejbca.core.protocol.ocsp.standalonesession.KeyRenewer.java
License:Open Source License
/** * Fetch a new certificate from EJBCA and stores the key with the certificate chain. * @param ejbcaWS from {@link #getEjbcaWS()} * @param userData from {@link #getUserDataVOWS(EjbcaWS, String)} * @param keyPair from {@link #generateKeyPair()} * @return the certificate chain of the stored key *///from ww w. j a v a2 s . co m private X509Certificate[] storeKey(EjbcaWS ejbcaWS, UserDataVOWS userData, KeyPair keyPair) { X509Certificate tmpCert = null; final Iterator<X509Certificate> i; try { final PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX509Name("CN=NOUSED"), keyPair.getPublic(), new DERSet(), keyPair.getPrivate(), this.privateKeyContainerKeyStore.providerName); final CertificateResponse certificateResponse = ejbcaWS.pkcs10Request(userData.getUsername(), userData.getPassword(), new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); i = (Iterator<X509Certificate>) CertificateFactory.getInstance("X.509") .generateCertificates(new ByteArrayInputStream(Base64.decode(certificateResponse.getData()))) .iterator(); } catch (Exception e) { m_log.error("Certificate generation problem.", e); return null; } while (i.hasNext()) { tmpCert = i.next(); try { tmpCert.verify(this.caChain.get(0).getPublicKey()); } catch (Exception e) { tmpCert = null; continue; } if (keyPair.getPublic().equals(tmpCert.getPublicKey())) { break; } tmpCert = null; } if (tmpCert == null) { m_log.error("No certificate signed by correct CA generated."); return null; } final List<X509Certificate> lCertChain = new ArrayList<X509Certificate>(this.caChain); lCertChain.add(0, tmpCert); final X509Certificate certChain[] = lCertChain.toArray(new X509Certificate[0]); if (this.privateKeyContainerKeyStore.fileName != null && this.privateKeyContainerKeyStore.sessionData.mKeyPassword == null) { m_log.error("Key password must be configured when updating SW keystore."); return null; } try { this.privateKeyContainerKeyStore.keyStore.setKeyEntry(this.privateKeyContainerKeyStore.alias, keyPair.getPrivate(), this.privateKeyContainerKeyStore.sessionData.mKeyPassword != null ? this.privateKeyContainerKeyStore.sessionData.mKeyPassword.toCharArray() : null, certChain); } catch (Throwable e) { m_log.error("Problem to store new key in HSM.", e); return null; } if (this.privateKeyContainerKeyStore.fileName != null) { try { this.privateKeyContainerKeyStore.keyStore.store( new FileOutputStream(this.privateKeyContainerKeyStore.fileName), this.privateKeyContainerKeyStore.sessionData.mStorePassword.toCharArray()); } catch (Throwable e) { m_log.error("Not possible to store keystore on file.", e); } } return certChain; }
From source file:org.ejbca.extra.db.CardRenewalResponse.java
License:Open Source License
/** * Default constructor that should be used. * /* w w w . java 2 s .co m*/ */ public CardRenewalResponse(long requestId, boolean success, String failinfo, Certificate authcert, Certificate signcert) { super(requestId, success, failinfo); try { data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(VERSION, Float.valueOf(LATEST_VERSION)); if (authcert != null) { String certstring = new String(Base64.encode(authcert.getEncoded())); data.put(AUTHCERT, certstring); } if (signcert != null) { String certstring = new String(Base64.encode(signcert.getEncoded())); data.put(SIGNCERT, certstring); } } catch (CertificateEncodingException e) { log.error("Certificate encoding failed", e); } }
From source file:org.ejbca.extra.db.CertificateRequestRequest.java
License:Open Source License
/** * Create a new certificate signing request message. * /* w w w . j a v a 2 s.co m*/ * @param requestId should be unique. * @param username The end entity identifier * @param password The shared secret * @param requestType one of REQUEST_TYPE_.. * @param requestData encoded request data in requestType format * @param responseType one of RESPONSE_TYPE_ */ public CertificateRequestRequest(long requestId, String username, String password, int requestType, byte[] requestData, int responseType) { data.put(VERSION, Float.valueOf(LATEST_VERSION)); data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(REQUESTID, Long.valueOf(requestId)); data.put(USERNAME, username); data.put(PASSWORD, password); data.put(REQUEST_TYPE, Integer.valueOf(requestType)); data.put(REQUEST_DATA, new String(Base64.encode(requestData))); data.put(RESPONSE_TYPE, Integer.valueOf(responseType)); }
From source file:org.ejbca.extra.db.CertificateRequestRequest.java
License:Open Source License
/** * Creates a new instance of CertificateRequestRequest. *//from w w w .ja v a 2 s .c om * @param requestId Unique request ID. * @param username The end entity name. * @param subjectDN The subject DN. * @param subjectAltName The subjectAltName or null. * @param email The e-mail address or null. * @param subjectDirectoryAttributes The subjectDirectoryAttributes or null. * @param endEntityProfileName The end entity profile name for instance "EMPTY". * @param certificateProfileName The certificate profile name for instance "ENDUSER". * @param cAName The CA name. * @param certificateSerialNo The certificate serial number to use or null, used to request a custom certificate serial number, if the CA allows this. * @param password The end entity password to set. * @param requestType One of REQUEST_TYPE_... * @param requestData Encoded request data in requestType format. * @param responseType One of RESPONSE_TYPE_... */ public CertificateRequestRequest(long requestId, String username, String subjectDN, String subjectAltName, String email, String subjectDirectoryAttributes, String endEntityProfileName, String certificateProfileName, String cAName, BigInteger certificateSerialNo, String password, int requestType, byte[] requestData, int responseType) { super(requestId, username, subjectDN, subjectAltName, email, subjectDirectoryAttributes, endEntityProfileName, certificateProfileName, cAName); data.put(VERSION, Float.valueOf(LATEST_VERSION)); data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(CERTIFICATESERIALNO, certificateSerialNo); data.put(PASSWORD, password); data.put(REQUEST_TYPE, Integer.valueOf(requestType)); data.put(REQUEST_DATA, new String(Base64.encode(requestData))); data.put(RESPONSE_TYPE, Integer.valueOf(responseType)); }
From source file:org.ejbca.extra.db.CertificateRequestResponse.java
License:Open Source License
/** * Create a new message./*w w w. ja 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 responseType One of the CertificateRequestRequest.RESPONSE_TYPE_ constants * @param responseData The request * * @see org.ejbca.extra.db.ExtRAResponse#ExtRAResponse(long, boolean, String) */ public CertificateRequestResponse(long requestId, boolean success, String failinfo, Integer responseType, byte[] responseData) { super(requestId, success, failinfo); data.put(VERSION, Float.valueOf(LATEST_VERSION)); data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(RESPONSE_TYPE, responseType); if (responseData != null) { data.put(RESPONSE_DATA, new String(Base64.encode(responseData))); } else { data.put(RESPONSE_DATA, null); } }