List of usage examples for java.math BigInteger toByteArray
public byte[] toByteArray()
From source file:net.sf.dsig.verify.OCSPHelper.java
/** * Check with OCSP protocol whether a certificate is valid * /* w w w .j a v a2s .c o m*/ * @param certificate an {@link X509Certificate} object * @return true if the certificate is valid; false otherwise * @throws NetworkAccessException when any network access issues occur * @throws VerificationException when an OCSP related error occurs */ public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException { PostMethod post = null; try { CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate, certificate.getSerialNumber()); OCSPReqGenerator gen = new OCSPReqGenerator(); gen.addRequest(cid); // Nonce BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Vector oids = new Vector(); Vector values = new Vector(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray()))); values.add(new X509Extension(false, new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray()))); gen.setRequestExtensions(new X509Extensions(oids, values)); // Requestor name - not really required, but added for completeness // gen.setRequestorName( // new GeneralName( // new X509Name( // certificate.getSubjectX500Principal().getName()))); logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16) + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName=" + caCertificate.getSubjectX500Principal().getName()); // TODO Need to call the generate(...) method, that signs the // request. Which means, need to have a keypair for that, too OCSPReq req = gen.generate(); // First try finding the OCSP access location in the X.509 certificate String uriAsString = getOCSPAccessLocationUri(certificate); // If not found, try falling back to the default if (uriAsString == null) { uriAsString = defaultOcspAccessLocation; } // If still null, bail out if (uriAsString == null) { throw new ConfigurationException( "OCSP AccessLocation not found on certificate, and no default set"); } HostConfiguration config = getHostConfiguration(); post = new PostMethod(uriAsString); post.setRequestHeader("Content-Type", "application/ocsp-request"); post.setRequestHeader("Accept", "application/ocsp-response"); post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded())); getHttpClient().executeMethod(config, post); logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine=" + post.getStatusLine()); if (post.getStatusCode() != HttpStatus.SC_OK) { throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine()); } byte[] responseBodyBytes = post.getResponseBody(); OCSPResp ocspRes = new OCSPResp(responseBodyBytes); if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) { // One possible exception is the use of a wrong CA certificate throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate" + "; status=" + ocspRes.getStatus()); } BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject(); SingleResp[] responses = res.getResponses(); SingleResp response = responses[0]; CertificateStatus status = (CertificateStatus) response.getCertStatus(); // Normal OCSP protocol allows a null status return status == null || status == CertificateStatus.GOOD; } catch (IOException e) { throw new NetworkAccessException("I/O error occured", e); } catch (OCSPException e) { throw new VerificationException("Error while following OCSP protocol", e); } finally { if (post != null) { post.releaseConnection(); } } }
From source file:co.rsk.mine.MinerServerImpl.java
public MinerWork updateGetWork(@Nonnull final Block block, @Nonnull final boolean notify) { Sha3Hash blockMergedMiningHash = new Sha3Hash(block.getHashForMergedMining()); BigInteger targetBI = DifficultyUtils.difficultyToTarget(block.getDifficultyBI()); byte[] targetUnknownLengthArray = targetBI.toByteArray(); byte[] targetArray = new byte[32]; System.arraycopy(targetUnknownLengthArray, 0, targetArray, 32 - targetUnknownLengthArray.length, targetUnknownLengthArray.length); logger.debug("Sending work for merged mining. Hash: " + block.getShortHashForMergedMining()); return new MinerWork(TypeConverter.toJsonHex(blockMergedMiningHash.getBytes()), TypeConverter.toJsonHex(targetArray), block.getFeesPaidToMiner(), notify, TypeConverter.toJsonHex(block.getParentHash())); }
From source file:org.sakaiproject.nakamura.cluster.ClusterTrackingServiceImpl.java
/** * {@inheritDoc}//from ww w . j av a 2s .c o m * * @see org.sakaiproject.nakamura.api.cluster.ClusterTrackingService#getClusterUniqueId() */ public String getClusterUniqueId() { synchronized (lockObject) { do { next = System.currentTimeMillis() - epoch; } while (next == prev); } BigInteger idNum = new BigInteger(String.valueOf(serverNumber) + String.valueOf(next)); prev = next; Base64 b64 = new Base64(); return b64.encodeToString(idNum.toByteArray()).trim(); }
From source file:org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension.java
private ASN1Encodable parseDERBitString(String value) throws CertificateExtensionException { ASN1Encodable retval = null;// w w w .j a v a2s . c om try { BigInteger bigInteger = new BigInteger(value, 2); int padBits = value.length() - 1 - value.lastIndexOf("1"); if (padBits == 8) { padBits = 0; } byte[] byteArray = bigInteger.toByteArray(); if (byteArray[0] == 0) { // Remove empty extra byte // System.arraycopy handles creating of temporary array when destinatio is the same System.arraycopy(byteArray, 1, byteArray, 0, byteArray.length - 1); } retval = new DERBitString(byteArray, padBits); } catch (NumberFormatException e) { throw new CertificateExtensionException(intres.getLocalizedMessage("certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID())); } return retval; }
From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtension.java
private DEREncodable parseDERBitString(String value) throws CertificateExtentionConfigurationException { DEREncodable retval = null;// w ww . j a v a 2s. c om try { BigInteger bigInteger = new BigInteger(value, 2); int padBits = value.length() - 1 - value.lastIndexOf("1"); if (padBits == 8) { padBits = 0; } byte[] byteArray = bigInteger.toByteArray(); if (byteArray[0] == 0) { // Remove empty extra byte byte[] shorterByteArray = new byte[byteArray.length - 1]; for (int i = 0; i < shorterByteArray.length; i++) { shorterByteArray[i] = byteArray[i + 1]; } byteArray = shorterByteArray; } retval = new DERBitString(byteArray, padBits); } catch (NumberFormatException e) { throw new CertificateExtentionConfigurationException(intres .getLocalizedMessage("certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID())); } return retval; }
From source file:org.cesecore.certificates.endentity.ExtendedInformation.java
/** * @param sn//from ww w . ja va2 s . co m * the serial number to be used for the certificate */ public void setCertificateSerialNumber(BigInteger sn) { if (sn == null) { this.data.remove(CERTIFICATESERIALNUMBER); return; } final String s = new String(Base64.encode(sn.toByteArray())); this.data.put(CERTIFICATESERIALNUMBER, s); }
From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.ocsp.OCSPVerifier.java
/** * This method generates an OCSP Request to be sent to an OCSP endpoint. * /*from w ww . j av a 2 s .c om*/ * @param issuerCert * is the Certificate of the Issuer of the peer certificate we * are interested in. * @param serialNumber * of the peer certificate. * @return generated OCSP request. * @throws CertificateVerificationException * */ private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws CertificateVerificationException { // TODO: Have to check if this is OK with synapse implementation. // Add provider BC // Security.addProvider(new // org.bouncycastle.jce.provider.BouncyCastleProvider()); try { // CertID structure is used to uniquely identify certificates that // are the subject of // an OCSP request or response and has an ASN.1 definition. CertID // structure is defined in RFC 2560 CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber); // basic request generation with nonce OCSPReqGenerator generator = new OCSPReqGenerator(); generator.addRequest(id); // create details for nonce extension. The nonce extension is used // to bind // a request to a response to prevent replay attacks. As the name // implies, // the nonce value is something that the client should only use once // within a reasonably small period. BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); // Vector<DERObjectIdentifier> objectIdentifiers = new // Vector<DERObjectIdentifier>(); // Vector<X509Extension> values = new Vector<X509Extension>(); X509Extension ext = new X509Extension(false, new DEROctetString(nonce.toByteArray())); Hashtable exts = new Hashtable(); exts.put(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.2"), ext); // to create the request Extension // objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); // values.add(ext); generator.setRequestExtensions(new X509Extensions(exts)); return generator.generate(); } catch (OCSPException e) { throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate", e); } }
From source file:org.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java
/** * This method generates an OCSP Request to be sent to an OCSP endpoint. * * @param issuerCert is the Certificate of the Issuer of the peer certificate we are interested in. * @param serialNumber of the peer certificate. * @return generated OCSP request.//from ww w . j a v a 2 s .c o m * @throws CertificateVerificationException */ private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws CertificateVerificationException { //TODO: Have to check if this is OK with synapse implementation. //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); try { // CertID structure is used to uniquely identify certificates that are the subject of // an OCSP request or response and has an ASN.1 definition. CertID structure is defined // in RFC 2560 CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber); // basic request generation with nonce OCSPReqGenerator generator = new OCSPReqGenerator(); generator.addRequest(id); // create details for nonce extension. The nonce extension is used to bind // a request to a response to prevent replay attacks. As the name implies, // the nonce value is something that the client should only use once within a reasonably // small period. BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Vector<ASN1ObjectIdentifier> objectIdentifiers = new Vector<ASN1ObjectIdentifier>(); Vector<X509Extension> values = new Vector<X509Extension>(); //to create the request Extension objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray()))); generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values)); return generator.generate(); } catch (OCSPException e) { throw new CertificateVerificationException( "Cannot generate OCSP Request with the " + "given certificate", e); } }
From source file:org.ojai.json.impl.JsonStreamDocumentReader.java
@Override public ByteBuffer getDecimalValueAsBytes() { BigDecimal decimal = getDecimal(); if (decimal != null) { BigInteger decimalInteger = decimal.unscaledValue(); byte[] bytearray = decimalInteger.toByteArray(); return ByteBuffer.wrap(bytearray); }/*from w w w. j av a 2s .com*/ return null; }
From source file:com.cloud.utils.net.NetUtils.java
public static String getIp6FromRange(final String ip6Range) { final String[] ips = ip6Range.split("-"); final String startIp = ips[0]; final IPv6Address start = IPv6Address.fromString(startIp); final BigInteger gap = countIp6InRange(ip6Range); BigInteger next = new BigInteger(gap.bitLength(), s_rand); while (next.compareTo(gap) >= 0) { next = new BigInteger(gap.bitLength(), s_rand); }//from w w w. ja v a2s . com InetAddress resultAddr = null; final BigInteger startInt = convertIPv6AddressToBigInteger(start); if (startInt != null) { final BigInteger resultInt = startInt.add(next); try { resultAddr = InetAddress.getByAddress(resultInt.toByteArray()); } catch (final UnknownHostException e) { return null; } } if (resultAddr != null) { final IPv6Address ip = IPv6Address.fromInetAddress(resultAddr); return ip.toString(); } return null; }