List of usage examples for java.math BigInteger valueOf
private static BigInteger valueOf(int val[])
From source file:strat.mining.stratum.proxy.Launcher.java
/** * Check that a valid SSl certificate already exists. If not, create a new * one.//from www. j a va 2s. co m * * @throws Exception */ private static void checkCertificate() throws Exception { File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME); KeyStore keyStore = KeyStore.getInstance("JKS"); if (!storeFile.exists()) { LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath()); storeFile.getParentFile().mkdirs(); storeFile.createNewFile(); keyStore.load(null, null); LOGGER.info("Generating new SSL certificate."); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator(); keyGenerator .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14)); AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair(); RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate(); RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getExponent()); RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic(); RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec); PublicKey rsaPub = kf.generatePublic(rsaPublicSpec); X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); Integer randomNumber = new SecureRandom().nextInt(); BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); byte[] publickeyb = rsaPub.getEncoded(); ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb); SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore, notAfter, subjectDN, subPubKeyInfo); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keysPair.getPrivate()); X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner); Certificate certificate = new CertificateFactory() .engineGenerateCertificate(new ByteBufferBackedInputStream( ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded()))); LOGGER.info("Certificate generated."); keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { certificate }); keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray()); } }
From source file:info.estebanluengo.alfrescoAPI.AlfrescoAPI.java
/** * Creates a new Document in the folder with the name, content, and mimeType, docType and properties given in the method call * //w ww.j a v a 2 s .c o m * @param session a Session object that is connected with the server * @param folder a Folder object where the new document will be created * @param fileName a String that contain the file name * @param content a byte array that contain the document * @param mimeType a String that represent the mime type of the document * @param docType a String that represent the document type. If it is null then CUSTOM_DOCUMENT_TYPE will be used * @param docProps a Map with the properties to are associated to the document. It may be null * * @return a Document object that represent the document that has just been created * @throws CmisContentAlreadyExistsException if the document to be created exists in the same folder */ public static Document createDocument(Session session, Folder folder, String fileName, byte[] content, String mimeType, String docType, Map<String, Object> docProps) throws CmisContentAlreadyExistsException { logger.debug("createDocument called for document name:" + fileName); if (docProps == null) { docProps = new HashMap<>(); } docProps.put(PropertyIds.NAME, fileName); docProps.put(PropertyIds.OBJECT_TYPE_ID, docType == null ? CUSTOM_DOCUMENT_TYPE : docType); ByteArrayInputStream in = new ByteArrayInputStream(content); ContentStream contentStream = new ContentStreamImpl(fileName, BigInteger.valueOf(content.length), mimeType, in); ObjectId documentId = session.createDocument(docProps, session.createObjectId((String) folder.getPropertyValue(PropertyIds.OBJECT_ID)), contentStream, VersioningState.MAJOR); logger.debug("Document created with id:" + documentId.getId()); Document document = (Document) session.getObject(documentId); return document; }
From source file:mitm.common.security.crl.PKIXRevocationChecker.java
private DeltaCRLStatus getDeltaCRLStatus(X509Certificate targetCertificate, X509CRL deltaCRL, PublicKey issuerPublicKey, Date now) throws NoSuchProviderException { DeltaCRLStatus status = DeltaCRLStatus.UNKNOWN; BigInteger baseCRLNumber;/*ww w .j av a 2 s. c o m*/ try { baseCRLNumber = X509CRLInspector.getDeltaIndicator(deltaCRL); } catch (IOException e) { logger.error("Error getting base CRL number", e); return DeltaCRLStatus.UNKNOWN; } X509CRLSelector crlSelector = new X509CRLSelector(); /* We need to find a valid base CRL with the same issuer as the delta CRL */ crlSelector.addIssuer(deltaCRL.getIssuerX500Principal()); /* * we need to find a baseCRL with at least a CRL number specified by the DeltaCRLIndicator in * the delta CRL */ crlSelector.setMinCRLNumber(baseCRLNumber); BigInteger deltaCRLNumber = null; try { deltaCRLNumber = X509CRLInspector.getCRLNumber(deltaCRL); } catch (IOException e) { logger.error("Error getting CRLNumber extension from the delta CRL.", e); } if (deltaCRLNumber != null) { /* * the base CRL we need to find should have a CRL number less than the delta CRL * otherwise it cannot be a base for this delta CRL */ crlSelector.setMaxCRLNumber(deltaCRLNumber.subtract(BigInteger.valueOf(1))); List<X509CRL> crls = findCRLs(targetCertificate, crlSelector, issuerPublicKey, now); for (X509CRL baseCRL : crls) { try { if (checkDeltaCRL_6_3_3_b(targetCertificate, deltaCRL, baseCRL)) { status = DeltaCRLStatus.OK; break; } } catch (IOException e) { logger.error("Error executing checkDeltaCRL_6_3_3_b.", e); continue; } if (hasUnsupportedCriticalExtensions(baseCRL)) { logger.warn("The base CRL has unsupported critical extensions."); status = DeltaCRLStatus.UNSUPPORTED_CRITICAL_EXTENSION; continue; } } } return status; }
From source file:org.tsm.concharto.service.EventSearchServiceHib.java
private SQLQuery createQuery(String prefix, Geometry boundingBox, SearchParams params) { StringBuffer select = new StringBuffer(prefix).append(SQL_SELECT_STUB); select.append(SQL_TIME_JOIN); //always join on time, so we can order by time StringBuffer clause = new StringBuffer(); boolean hasConjuncted = false; if (params.getVisibility() == Visibility.NORMAL) { hasConjuncted = addClause(hasConjuncted, clause, SQL_VISIBLE_CLAUSE); } else if (params.getVisibility() == Visibility.HIDDEN) { hasConjuncted = addClause(hasConjuncted, clause, SQL_HIDDEN_CLAUSE); } else if (params.getVisibility() == Visibility.FLAGGED) { hasConjuncted = addClause(hasConjuncted, clause, SQL_FLAGGED_CLAUSE); }/*from ww w . jav a2s. c o m*/ if (!StringUtils.isEmpty(params.getTextFilter())) { select.append(SQL_SEARCH_JOIN); hasConjuncted = addClause(hasConjuncted, clause, SQL_MATCH_CLAUSE); } if (boundingBox != null) { select.append(SQL_GEO_JOIN); hasConjuncted = addClause(hasConjuncted, clause, SQL_MBRWITHIN_CLAUSE); } if (params.getTimeRange() != null) { if (params.isIncludeTimeRangeOverlaps()) { addClause(hasConjuncted, clause, SQL_TIMERANGE_CLAUSE); } else { addClause(hasConjuncted, clause, SQL_TIMERANGE_EXCLUDE_OVERLAPS_CLAUSE); } } if (!StringUtils.isEmpty(params.getUserTag())) { //special case for empty tags if (!UNTAGGED.equals(params.getUserTag())) { select.append(SQL_TAG_JOIN); hasConjuncted = addClause(hasConjuncted, clause, SQL_TAG_CLAUSE); } else { select.append(SQL_TAG_EMPTY_JOIN); hasConjuncted = addClause(hasConjuncted, clause, SQL_TAG_EMPTY_CLAUSE); } } if (!StringUtils.isEmpty(params.getCatalog())) { hasConjuncted = addClause(hasConjuncted, clause, SQL_CATALOG_CLAUSE); } clause.append(SQL_ORDER_CLAUSE); select.append(clause); // Note: Hibernate always uses prepared statements SQLQuery sqlQuery = this.sessionFactory.getCurrentSession().createSQLQuery(select.toString()); if (boundingBox != null) { sqlQuery.setString(PARAM_GEOM_TEXT, boundingBox.toText()); } if (!StringUtils.isEmpty(params.getTextFilter())) { sqlQuery.setString(PARAM_SEARCH_TEXT, params.getTextFilter()); } if (!StringUtils.isEmpty(params.getUserTag())) { //special case for empty tags if (!UNTAGGED.equals(params.getUserTag())) { sqlQuery.setString(PARAM_TAG, StringUtils.trim(params.getUserTag())); } } if (!StringUtils.isEmpty(params.getCatalog())) { sqlQuery.setString(PARAM_CATALOG, StringUtils.trim(params.getCatalog())); } if (params.getTimeRange() != null) { sqlQuery.setBigInteger(PARAM_EARLIEST, BigInteger.valueOf(params.getTimeRange().getBegin().getDate().getTime())); sqlQuery.setBigInteger(PARAM_LATEST, BigInteger.valueOf(params.getTimeRange().getEnd().getDate().getTime())); } return sqlQuery; }
From source file:com.google.jenkins.plugins.storage.AbstractUpload.java
/** * This is the workhorse API for performing the actual uploads. It is * performed at the workspace, so that all of the {@link FilePath}s should * be local./*from www . j av a 2 s .c o m*/ */ private void performUploads(Map<String, String> metadata, String bucketName, String objectPrefix, GoogleRobotCredentials credentials, UploadSpec uploads, TaskListener listener) throws UploadException { try { Storage service = module.getStorageService(credentials); Executor executor = module.newExecutor(); // Ensure the bucket exists, fetching it regardless so that we can // attach its default ACLs to the objects we upload. Bucket bucket = getOrCreateBucket(service, credentials, executor, bucketName); for (FilePath include : uploads.inclusions) { String relativePath = getRelative(include, uploads.workspace); String uploadedFileName = getStrippedFilename(relativePath); String finalName = FilenameUtils .separatorsToUnix(FilenameUtils.concat(objectPrefix, uploadedFileName)); StorageObject object = new StorageObject().setName(finalName).setMetadata(metadata) .setContentDisposition(HttpHeaders.getContentDisposition(include.getName())) .setContentType(detectMIMEType(include.getName())) .setSize(BigInteger.valueOf(include.length())); if (isSharedPublicly()) { object.setAcl(addPublicReadAccess(getDefaultObjectAcl(bucket, listener))); } // Give clients an opportunity to decorate the storage // object before we store it. annotateObject(object, listener); // Log that we are uploading the file and begin executing the upload. listener.getLogger().println(module.prefix(Messages.AbstractUpload_Uploading(relativePath))); performUploadWithRetry(executor, service, bucket, object, include); } } catch (ForbiddenException e) { // If the user doesn't own a bucket then they will end up here. throw new UploadException(Messages.AbstractUpload_ForbiddenFileUpload(), e); } catch (ExecutorException e) { throw new UploadException(Messages.AbstractUpload_ExceptionFileUpload(), e); } catch (IOException e) { throw new UploadException(Messages.AbstractUpload_ExceptionFileUpload(), e); } catch (InterruptedException e) { throw new UploadException(Messages.AbstractUpload_ExceptionFileUpload(), e); } }
From source file:com.github.jrrdev.mantisbtsync.core.jobs.enums.EnumsReadersTest.java
/** * Generate items for the tests.//from w w w.ja v a2 s .co m * * @param operation * Operation name * @return items */ private ObjectRef[] generateItems(final String operation) { final ObjectRef[] items = new ObjectRef[] { new ObjectRef(BigInteger.valueOf(1), operation + "_1"), new ObjectRef(BigInteger.valueOf(2), operation + "_2") }; return items; }
From source file:jp.aegif.nemaki.cmis.aspect.impl.CompileServiceImpl.java
@Override public <T extends Content> ObjectList compileObjectDataList(CallContext callContext, String repositoryId, List<T> contents, String filter, Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter, Boolean includeAcl, BigInteger maxItems, BigInteger skipCount, boolean folderOnly, String orderBy) { if (CollectionUtils.isEmpty(contents)) { //Empty list ObjectListImpl list = new ObjectListImpl(); list.setObjects(new ArrayList<ObjectData>()); list.setNumItems(BigInteger.ZERO); list.setHasMoreItems(false);/*from ww w .ja va 2 s .c o m*/ return list; } else { List<ObjectData> ods = new ArrayList<ObjectData>(); for (T c : contents) { //Filter by folderOnly if (folderOnly && !c.isFolder()) { continue; } //Get each ObjectData ObjectData _od; ObjectData v = nemakiCachePool.get(repositoryId).getObjectDataCache().get(c.getId()); if (v == null) { _od = compileObjectDataWithFullAttributes(callContext, repositoryId, c); } else { _od = (ObjectDataImpl) v; } ObjectData od = filterObjectDataInList(callContext, repositoryId, _od, filter, includeAllowableActions, includeRelationships, renditionFilter, includeAcl); if (od != null) { ods.add(od); } } //Sort sortUtil.sort(repositoryId, ods, orderBy); //Set metadata ObjectListImpl list = new ObjectListImpl(); Integer _skipCount = skipCount.intValue(); Integer _maxItems = maxItems.intValue(); if (_skipCount >= ods.size()) { list.setHasMoreItems(false); list.setObjects(new ArrayList<ObjectData>()); } else { //hasMoreItems Boolean hasMoreItems = _skipCount + _maxItems < ods.size(); list.setHasMoreItems(hasMoreItems); //paged list Integer toIndex = Math.min(_skipCount + _maxItems, ods.size()); list.setObjects(new ArrayList<>(ods.subList(_skipCount, toIndex))); } //totalNumItem list.setNumItems(BigInteger.valueOf(ods.size())); return list; } }
From source file:org.pgptool.gui.encryption.implpgp.EncryptionServicePgpImpl.java
@Override public void decrypt(String sourceFile, String targetFile, PasswordDeterminedForKey keyAndPassword, ProgressHandler optionalProgressHandler, OutputStreamSupervisor optionalOutputStreamSupervisor) throws InvalidPasswordException, UserRequestedCancellationException { OutputStreamSupervisor outputStreamSupervisor = optionalOutputStreamSupervisor != null ? optionalOutputStreamSupervisor : new OutputStreamSupervisorImpl(); log.debug("Decrypting " + sourceFile); Updater progress = null;//w ww . j a va 2s . co m BigInteger sourceSize = BigInteger.valueOf(new File(sourceFile).length()); if (optionalProgressHandler != null) { progress = Progress.create("action.decrypt", optionalProgressHandler); progress.updateStepInfo("progress.preparingKeys", FilenameUtils.getName(sourceFile)); progress.updateTotalSteps(sourceSize); } Key decryptionKey = keyAndPassword.getMatchedKey(); String passphrase = keyAndPassword.getPassword(); Preconditions.checkArgument(StringUtils.hasText(sourceFile) && new File(sourceFile).exists(), "Source file name must be correct"); Preconditions.checkArgument(StringUtils.hasText(targetFile), "Target file name must be provided"); Preconditions.checkArgument(decryptionKey != null, "decryption key must be provided"); Preconditions.checkArgument(StringUtils.hasText(passphrase), "Passphrase must be provided"); InputStream in = null; try { PGPSecretKey secretKey = KeyDataPgp.get(decryptionKey) .findSecretKeyById(keyAndPassword.getDecryptionKeyId()); PGPPrivateKey privateKey = getPrivateKey(passphrase, secretKey); CountingInputStream countingStream = new CountingInputStream(new FileInputStream(sourceFile)); in = new BufferedInputStream(countingStream); PGPPublicKeyEncryptedData publicKeyEncryptedData = getPublicKeyEncryptedDataByKeyId(in, secretKey); OutputStream outputStream = outputStreamSupervisor.get(targetFile); decryptStream(publicKeyEncryptedData, privateKey, outputStream, progress, countingStream); if (optionalProgressHandler != null) { // NOTE: The problem with decryption is that BC doesn't provide API to get // compressed+encrypted file size so it's hard to report progress precisely. We // do our best, but still it's very approximate. So that's why we need to // explicitly set 100% after operation was completed progress.updateTotalSteps(sourceSize); } } catch (Throwable t) { File fileToDelete = new File(targetFile); if (fileToDelete.exists() && !fileToDelete.delete()) { log.warn("Failed to delete file after failed decryption: " + targetFile); } Throwables.throwIfInstanceOf(t, InvalidPasswordException.class); Throwables.throwIfInstanceOf(t, UserRequestedCancellationException.class); log.error("Decryption failed", t); throw new RuntimeException("Decryption failed", t); } finally { IoStreamUtils.safeClose(in); } }
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 . jav a 2s .c o m*/ /* 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:net.pms.util.Rational.java
/** * Returns an instance with the given {@code numerator} and * {@code denominator}./*from www . j a v a 2 s . c o m*/ * * @param numerator the numerator. * @param denominator the denominator. * @return An instance that represents the value of {@code numerator}/ * {@code denominator}. */ @Nonnull public static Rational valueOf(long numerator, long denominator) { if (numerator == 0 && denominator == 0) { return NaN; } if (denominator == 0) { return numerator > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY; } if (numerator == 0) { return ZERO; } if (numerator == denominator) { return ONE; } BigInteger biNumerator; BigInteger biDenominator; if (denominator < 0) { biNumerator = BigInteger.valueOf(-numerator); biDenominator = BigInteger.valueOf(-denominator); } else { biNumerator = BigInteger.valueOf(numerator); biDenominator = BigInteger.valueOf(denominator); } long gcd = calculateGreatestCommonDivisor(numerator, denominator); BigInteger greatestCommonDivisor = BigInteger.valueOf(gcd); BigInteger reducedNumerator; BigInteger reducedDenominator; if (gcd == 1) { reducedNumerator = biNumerator; reducedDenominator = biDenominator; } else { reducedNumerator = biNumerator.divide(greatestCommonDivisor); reducedDenominator = biDenominator.divide(greatestCommonDivisor); } return new Rational(biNumerator, biDenominator, greatestCommonDivisor, reducedNumerator, reducedDenominator); }