List of usage examples for java.math BigInteger toString
public String toString(int radix)
From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java
License:asdf
@Override public Certificate findCertificateByIssuerAndSerno(String issuerDN, BigInteger serno) { if (log.isTraceEnabled()) { log.trace(">findCertificateByIssuerAndSerno(), dn:" + issuerDN + ", serno=" + serno.toString(16)); }//from ww w . j av a2 s .c o m // First make a DN in our well-known format String dn = CertTools.stringToBCDNString(StringTools.strip(issuerDN)); if (log.isDebugEnabled()) { log.debug("Looking for cert with (transformed)DN: " + dn); } Collection<CertificateData> coll = CertificateData.findByIssuerDNSerialNumber(entityManager, dn, serno.toString()); Certificate ret = null; if (coll.size() > 1) { String msg = INTRES.getLocalizedMessage("store.errorseveralissuerserno", issuerDN, serno.toString(16)); log.error(msg); } Certificate cert = null; // There are several certs, we will try to find the latest issued one for (CertificateData certificateData : coll) { cert = certificateData.getCertificate(this.entityManager); if (ret != null) { if (CertTools.getNotBefore(cert).after(CertTools.getNotBefore(ret))) { // cert is never than ret ret = cert; } } else { ret = cert; } } if (log.isTraceEnabled()) { log.trace("<findCertificateByIssuerAndSerno(), dn:" + issuerDN + ", serno=" + serno.toString(16)); } return ret; }
From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java
License:asdf
@Override public String getCADnFromRequest(final RequestMessage req) { String dn = req.getIssuerDN(); if (log.isDebugEnabled()) { log.debug("Got an issuerDN: " + dn); }//from w ww .java 2 s . c o m // If we have issuer and serialNo, we must find the CA certificate, to get the CAs subject name // If we don't have a serialNumber, we take a chance that it was actually the subjectDN (for example a RootCA) final BigInteger serno = req.getSerialNo(); if (serno != null) { if (log.isDebugEnabled()) { log.debug("Got a serialNumber: " + serno.toString(16)); } final Certificate cert = findCertificateByIssuerAndSerno(dn, serno); if (cert != null) { dn = CertTools.getSubjectDN(cert); } } if (log.isDebugEnabled()) { log.debug("Using DN: " + dn); } return dn; }
From source file:com.cloud.storage.resource.NfsSecondaryStorageResource.java
private Answer execute(ComputeChecksumCommand cmd) { String relativeTemplatePath = cmd.getTemplatePath(); String parent = getRootDir(cmd); if (relativeTemplatePath.startsWith(File.separator)) { relativeTemplatePath = relativeTemplatePath.substring(1); }/*www. ja v a 2 s . co m*/ if (!parent.endsWith(File.separator)) { parent += File.separator; } String absoluteTemplatePath = parent + relativeTemplatePath; MessageDigest digest; String checksum = null; File f = new File(absoluteTemplatePath); InputStream is = null; byte[] buffer = new byte[8192]; int read = 0; if (s_logger.isDebugEnabled()) { s_logger.debug("parent path " + parent + " relative template path " + relativeTemplatePath); } try { digest = MessageDigest.getInstance("MD5"); is = new FileInputStream(f); while ((read = is.read(buffer)) > 0) { digest.update(buffer, 0, read); } byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); checksum = bigInt.toString(16); if (s_logger.isDebugEnabled()) { s_logger.debug( "Successfully calculated checksum for file " + absoluteTemplatePath + " - " + checksum); } } catch (IOException e) { String logMsg = "Unable to process file for MD5 - " + absoluteTemplatePath; s_logger.error(logMsg); return new Answer(cmd, false, checksum); } catch (NoSuchAlgorithmException e) { return new Answer(cmd, false, checksum); } finally { try { if (is != null) is.close(); } catch (IOException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Could not close the file " + absoluteTemplatePath); } return new Answer(cmd, false, checksum); } } return new Answer(cmd, true, checksum); }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
/** * Md5/* w w w . jav a 2 s .c o m*/ * * @param data * * @return MD5 * * @throws IOException * IO */ public static String md5Sum(byte[] data) throws IOException { try { MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] md5sum = digest.digest(data); BigInteger bigInt = new BigInteger(1, md5sum); // Front load any zeros cut off by BigInteger String md5 = bigInt.toString(16); while (md5.length() != 32) { md5 = "0" + md5; } return md5; } catch (NoSuchAlgorithmException nsae) { logger.fatal("Major problems with your Java configuration", nsae); return null; } }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
/** * Md5/*from www. ja v a 2 s . c o m*/ * * @param f * * @return MD5 * * @throws IOException * IO */ public static String md5Sum(File f) throws IOException { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); InputStream is = new FileInputStream(f); byte[] buffer = new byte[1024]; int read = 0; while ((read = is.read(buffer)) > 0) { digest.update(buffer, 0, read); } is.close(); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); // Front load any zeros cut off by BigInteger String md5 = bigInt.toString(16); while (md5.length() != 32) { md5 = "0" + md5; } return md5; } catch (NoSuchAlgorithmException e) { logger.fatal("The JRE is misconfigured on this computer", e); return null; } }
From source file:org.ejbca.core.protocol.cmp.CrmfRARequestCustomSerialNoTest.java
/** * @param userDN/* w ww .j a va 2 s . c o m*/ * for new certificate. * @param keys * key of the new certificate. * @param sFailMessage * if !=null then EJBCA is expected to fail. The failure response * message string is checked against this parameter. * @return If it is a certificate request that results in a successful certificate issuance, this certificate is returned * @throws Exception */ private X509Certificate crmfHttpUserTest(X500Name userDN, KeyPair keys, String sFailMessage, BigInteger customCertSerno) throws Exception { X509Certificate ret = null; final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); final int reqId; { final PKIMessage one = genCertReq(this.issuerDN, userDN, keys, this.cacert, nonce, transid, true, null, null, null, customCertSerno, null, null); final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); assertNotNull(req); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, this.issuerDN, userDN, this.cacert, nonce, transid, sFailMessage == null, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); if (sFailMessage == null) { ret = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId); // verify if custom cert serial number was used if (customCertSerno != null) { assertTrue(ret.getSerialNumber().toString(16) + " is not same as expected " + customCertSerno.toString(16), ret.getSerialNumber().equals(customCertSerno)); } } else { checkCmpFailMessage(resp, sFailMessage, CmpPKIBodyConstants.ERRORMESSAGE, reqId, PKIFailureInfo.badRequest, PKIFailureInfo.incorrectData); } } { // Send a confirm message to the CA final String hash = "foo123"; final PKIMessage con = genCertConfirm(userDN, this.cacert, nonce, transid, hash, reqId); assertNotNull(con); PKIMessage confirm = protectPKIMessage(con, false, PBEPASSWORD, 567); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(confirm); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, userDN, this.cacert, nonce, transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); checkCmpPKIConfirmMessage(userDN, this.cacert, resp); } return ret; }
From source file:org.ejbca.core.protocol.cmp.CrmfRARequestTest.java
/** * @param userDN/*from www. j a va2 s.c o m*/ * for new certificate. * @param keys * key of the new certificate. * @param sFailMessage * if !=null then EJBCA is expected to fail. The failure response * message string is checked against this parameter. * @throws Exception */ private void crmfHttpUserTest(String userDN, KeyPair keys, String sFailMessage, BigInteger customCertSerno) throws Exception { // Create a new good user final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); final int reqId; { final PKIMessage one = genCertReq(issuerDN, userDN, keys, cacert, nonce, transid, true, null, null, null, customCertSerno); final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567); reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); assertNotNull(req); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, sFailMessage == null, null); if (sFailMessage == null) { X509Certificate cert = checkCmpCertRepMessage(userDN, cacert, resp, reqId); // verify if custom cert serial number was used if (customCertSerno != null) { assertTrue(cert.getSerialNumber().toString(16) + " is not same as expected " + customCertSerno.toString(16), cert.getSerialNumber().equals(customCertSerno)); } } else { checkCmpFailMessage(resp, sFailMessage, CmpPKIBodyConstants.ERRORMESSAGE, reqId, FailInfo.BAD_REQUEST.hashCode()); } } { // Send a confirm message to the CA final String hash = "foo123"; final PKIMessage con = genCertConfirm(userDN, cacert, nonce, transid, hash, reqId); assertNotNull(con); PKIMessage confirm = protectPKIMessage(con, false, PBEPASSWORD, 567); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(confirm); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200); checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, null); checkCmpPKIConfirmMessage(userDN, cacert, resp); } }
From source file:com.amazonaws.services.kinesis.producer.KinesisProducer.java
/** * Put a record asynchronously. A {@link ListenableFuture} is returned that * can be used to retrieve the result, either by polling or by registering a * callback./*from w w w . j a v a 2s .c o m*/ * * <p> * The return value can be disregarded if you do not wish to process the * result. Under the covers, the KPL will automatically reattempt puts in * case of transient errors (including throttling). A failed result is * generally returned only if an irrecoverable error is detected (e.g. * trying to put to a stream that doesn't exist), or if the record expires. * * <p> * <b>Thread safe.</b> * * <p> * To add a listener to the future: * <p> * <code> * ListenableFuture<PutRecordResult> f = myKinesisProducer.addUserRecord(...); * com.google.common.util.concurrent.Futures.addCallback(f, callback, executor); * </code> * <p> * where <code>callback</code> is an instance of * {@link com.google.common.util.concurrent.FutureCallback} and * <code>executor</code> is an instance of * {@link java.util.concurrent.Executor}. * <p> * <b>Important:</b> * <p> * If long-running tasks are performed in the callbacks, it is recommended * that a custom executor be provided when registering callbacks to ensure * that there are enough threads to achieve the desired level of * parallelism. By default, the KPL will use an internal thread pool to * execute callbacks, but this pool may not have a sufficient number of * threads if a large number is desired. * <p> * Another option would be to hand the result off to a different component * for processing and keep the callback routine fast. * * @param stream * Stream to put to. * @param partitionKey * Partition key. Length must be at least one, and at most 256 * (inclusive). * @param explicitHashKey * The hash value used to explicitly determine the shard the data * record is assigned to by overriding the partition key hash. * Must be a valid string representation of a positive integer * with value between 0 and <tt>2^128 - 1</tt> (inclusive). * @param data * Binary data of the record. Maximum size 1MiB. * @return A future for the result of the put. * @throws IllegalArgumentException * if input does not meet stated constraints * @throws DaemonException * if the child process is dead * @see ListenableFuture * @see UserRecordResult * @see KinesisProducerConfiguration#setRecordTtl(long) * @see UserRecordFailedException */ public ListenableFuture<UserRecordResult> addUserRecord(String stream, String partitionKey, String explicitHashKey, ByteBuffer data) { if (stream == null) { throw new IllegalArgumentException("Stream name cannot be null"); } stream = stream.trim(); if (stream.length() == 0) { throw new IllegalArgumentException("Stream name cannot be empty"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey cannot be null"); } if (partitionKey.length() < 1 || partitionKey.length() > 256) { throw new IllegalArgumentException( "Invalid parition key. Length must be at least 1 and at most 256, got " + partitionKey.length()); } try { partitionKey.getBytes("UTF-8"); } catch (Exception e) { throw new IllegalArgumentException("Partition key must be valid UTF-8"); } BigInteger b = null; if (explicitHashKey != null) { explicitHashKey = explicitHashKey.trim(); try { b = new BigInteger(explicitHashKey); } catch (NumberFormatException e) { throw new IllegalArgumentException( "Invalid explicitHashKey, must be an integer, got " + explicitHashKey); } if (b != null) { if (b.compareTo(UINT_128_MAX) > 0 || b.compareTo(BigInteger.ZERO) < 0) { throw new IllegalArgumentException( "Invalid explicitHashKey, must be greater or equal to zero and less than or equal to (2^128 - 1), got " + explicitHashKey); } } } if (data != null && data.remaining() > 1024 * 1024) { throw new IllegalArgumentException( "Data must be less than or equal to 1MB in size, got " + data.remaining() + " bytes"); } long id = messageNumber.getAndIncrement(); SettableFuture<UserRecordResult> f = SettableFuture.create(); futures.put(id, f); PutRecord.Builder pr = PutRecord.newBuilder().setStreamName(stream).setPartitionKey(partitionKey) .setData(data != null ? ByteString.copyFrom(data) : ByteString.EMPTY); if (b != null) { pr.setExplicitHashKey(b.toString(10)); } Message m = Message.newBuilder().setId(id).setPutRecord(pr.build()).build(); child.add(m); return f; }
From source file:org.ejbca.core.ejb.ra.UserAdminSessionBean.java
@TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override/*from ww w . j av a 2s.c o m*/ public void checkIfCertificateBelongToUser(Admin admin, BigInteger certificatesnr, String issuerdn) throws AuthorizationDeniedException { if (log.isTraceEnabled()) { log.trace(">checkIfCertificateBelongToUser(" + certificatesnr.toString(16) + ")"); } if (!WebConfiguration.getRequireAdminCertificateInDatabase()) { if (log.isTraceEnabled()) { log.trace("<checkIfCertificateBelongToUser Configured to ignore if cert belongs to user."); } return; } String username = certificateStoreSession.findUsernameByCertSerno(admin, certificatesnr, issuerdn); if (username != null) { if (UserData.findByUsername(entityManager, username) == null) { String msg = intres.getLocalizedMessage("ra.errorcertnouser", issuerdn, certificatesnr.toString(16)); logSession.log(admin, LogConstants.INTERNALCAID, LogConstants.MODULE_RA, new Date(), null, null, LogConstants.EVENT_ERROR_ADMINISTRATORLOGGEDIN, msg); throw new AuthorizationDeniedException(msg); } } if (log.isTraceEnabled()) { log.trace("<checkIfCertificateBelongToUser()"); } }
From source file:org.cesecore.certificates.ocsp.CanLogCache.java
/** * This method takes byte array and translates it onto a OCSPReq class. * /*from w w w. ja v a 2 s.com*/ * @param authenticationToken An authentication token needed to perform validation. * @param request the byte array in question. * @param remoteAddress The remote address of the HttpRequest associated with this array. * @param transactionLogger A transaction logger. * @return * @throws InvalidKeyException * @throws SignRequestException thrown if an unsigned request was processed when system configuration requires that all requests be signed. * @throws CertificateException * @throws NoSuchAlgorithmException * @throws SignRequestSignatureException */ private OCSPReq translateRequestFromByteArray(byte[] request, String remoteAddress, TransactionLogger transactionLogger) throws MalformedRequestException, SignRequestException, SignRequestSignatureException, CertificateException, NoSuchAlgorithmException { OCSPReq result = null; try { result = new OCSPReq(request); } catch (IOException e) { throw new MalformedRequestException("Could not form OCSP request", e); } if (result.getRequestorName() == null) { if (log.isDebugEnabled()) { log.debug("Requestor name is null"); } } else { if (log.isDebugEnabled()) { log.debug("Requestor name is: " + result.getRequestorName().toString()); } transactionLogger.paramPut(TransactionLogger.REQ_NAME, result.getRequestorName().toString()); } /** * check the signature if contained in request. if the request does not contain a signature and the servlet is configured in the way the a * signature is required we send back 'sigRequired' response. */ if (log.isDebugEnabled()) { log.debug("Incoming OCSP request is signed : " + result.isSigned()); } if (result.isSigned()) { X509Certificate signercert = checkRequestSignature(remoteAddress, result); String signercertIssuerName = CertTools.getIssuerDN(signercert); BigInteger signercertSerNo = CertTools.getSerialNumber(signercert); String signercertSubjectName = CertTools.getSubjectDN(signercert); transactionLogger.paramPut(TransactionLogger.SIGN_ISSUER_NAME_DN, signercertIssuerName); transactionLogger.paramPut(TransactionLogger.SIGN_SERIAL_NO, signercert.getSerialNumber().toByteArray()); transactionLogger.paramPut(TransactionLogger.SIGN_SUBJECT_NAME, signercertSubjectName); transactionLogger.paramPut(PatternLogger.REPLY_TIME, TransactionLogger.REPLY_TIME); if (OcspConfiguration.getEnforceRequestSigning()) { // If it verifies OK, check if it is revoked final CertificateStatus status = certificateStoreSession .getStatus(CertTools.getIssuerDN(signercert), CertTools.getSerialNumber(signercert)); /* * If rci == null it means the certificate does not exist in database, we then treat it as ok, because it may be so that only revoked * certificates is in the (external) OCSP database. */ if (status.equals(CertificateStatus.REVOKED)) { String serno = signercertSerNo.toString(16); String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.revoked", signercertSubjectName, signercertIssuerName, serno); log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } if (OcspConfiguration.getRestrictSignatures()) { DirectoryCache.INSTANCE.loadTrustDir(); switch (OcspConfiguration.getRestrictSignaturesByMethod()) { case OcspConfiguration.RESTRICTONSIGNER: if (!checkCertInList(signercert, DirectoryCache.INSTANCE.getTrustedReqSigSigners())) { String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed", signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16)); log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } break; case OcspConfiguration.RESTRICTONISSUER: X509Certificate signerca = certificateStoreSession .findLatestX509CertificateBySubject(signercertIssuerName); if ((signerca == null) || (!checkCertInList(signerca, DirectoryCache.INSTANCE.getTrustedReqSigIssuers()))) { String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed", signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16)); log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } break; default: // There must be an internal error. We do not want to send a response, just to be safe. throw new OcspFailureException( "m_reqRestrictMethod=" + OcspConfiguration.getRestrictSignaturesByMethod()); } } } } else { if (OcspConfiguration.getEnforceRequestSigning()) { // Signature required throw new SignRequestException("Signature required"); } } return result; }