List of usage examples for java.lang Byte SIZE
int SIZE
To view the source code for java.lang Byte SIZE.
Click Source Link
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
/** * Creates a new Cryptor with a newly initialized PRNG. *//*from w ww . j a va2 s . c o m*/ public Aes256Cryptor() { SECURE_PRNG.setSeed(SECURE_PRNG.generateSeed(PRNG_SEED_LENGTH)); byte[] bytes = new byte[AES_KEY_LENGTH_IN_BITS / Byte.SIZE]; try { SECURE_PRNG.nextBytes(bytes); this.primaryMasterKey = new SecretKeySpec(bytes, AES_KEY_ALGORITHM); SECURE_PRNG.nextBytes(bytes); this.hMacMasterKey = new SecretKeySpec(bytes, HMAC_KEY_ALGORITHM); } finally { Arrays.fill(bytes, (byte) 0); } }
From source file:net.ripe.rpki.commons.crypto.util.Asn1Util.java
/** * IPAddress ::= BIT STRING// w ww. jav a2s . c om */ public static IpAddress parseIpAddress(IpResourceType type, ASN1Encodable der, boolean padWithOnes) { expect(der, DERBitString.class); DERBitString derBitString = (DERBitString) der; byte[] bytes = derBitString.getBytes(); BigInteger value = new BigInteger(1, bytes); int usedBits = bytes.length * Byte.SIZE; int neededBits = type.getBitSize(); int padBits = derBitString.getPadBits(); if (padBits > 0) { byte lastByte = bytes[bytes.length - 1]; byte mask = (byte) ((1 << padBits) - 1); Validate.isTrue((lastByte & mask) == 0, "pad bits not zero"); } BigInteger upperBits = value.shiftLeft(neededBits - usedBits); BigInteger lowerBits = BigInteger.ZERO; if (padWithOnes) { lowerBits = BigInteger.ONE.shiftLeft(neededBits - usedBits + padBits).subtract(BigInteger.ONE); } return (IpAddress) type.fromBigInteger(upperBits.or(lowerBits)); }
From source file:com.facebook.buck.rules.HttpArtifactCache.java
public CacheResult fetchImpl(RuleKey ruleKey, File file) throws IOException { Request request = createRequestBuilder(ruleKey.toString()).get().build(); Response response = fetchCall(request); if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) { LOGGER.info("fetch(%s): cache miss", ruleKey); return CacheResult.MISS; }/*from ww w .j a va 2s .c o m*/ if (response.code() != HttpURLConnection.HTTP_OK) { LOGGER.warn("fetch(%s): unexpected response: %d", ruleKey, response.code()); return CacheResult.MISS; } // The hash code shipped with the artifact to/from the cache. HashCode expectedHashCode, actualHashCode; // Setup a temporary file, which sits next to the destination, to write to and // make sure all parent dirs exist. Path path = file.toPath(); projectFilesystem.createParentDirs(path); Path temp = projectFilesystem.createTempFile(path.getParent(), path.getFileName().toString(), ".tmp"); // Open the stream to server just long enough to read the hash code and artifact. try (DataInputStream input = new DataInputStream(response.body().byteStream())) { // First, extract the size of the file data portion, which we put in the beginning of // the artifact. long length = input.readLong(); // Now, write the remaining response data to the temp file, while grabbing the hash. try (BoundedInputStream boundedInput = new BoundedInputStream(input, length); HashingInputStream hashingInput = new HashingInputStream(hashFunction, boundedInput); OutputStream output = projectFilesystem.newFileOutputStream(temp)) { ByteStreams.copy(hashingInput, output); actualHashCode = hashingInput.hash(); } // Lastly, extract the hash code from the end of the request data. byte[] hashCodeBytes = new byte[hashFunction.bits() / Byte.SIZE]; ByteStreams.readFully(input, hashCodeBytes); expectedHashCode = HashCode.fromBytes(hashCodeBytes); // We should be at the end of output -- verify this. Also, we could just try to read a // single byte here, instead of all remaining input, but some network stack implementations // require that we exhaust the input stream before the connection can be reusable. try (OutputStream output = ByteStreams.nullOutputStream()) { if (ByteStreams.copy(input, output) != 0) { LOGGER.warn("fetch(%s): unexpected end of input", ruleKey); return CacheResult.MISS; } } } // Now form the checksum on the file we got and compare it to the checksum form the // the HTTP header. If it's incorrect, log this and return a miss. if (!expectedHashCode.equals(actualHashCode)) { LOGGER.warn("fetch(%s): artifact had invalid checksum", ruleKey); projectFilesystem.deleteFileAtPath(temp); return CacheResult.MISS; } // Finally, move the temp file into it's final place. projectFilesystem.move(temp, path, StandardCopyOption.REPLACE_EXISTING); LOGGER.info("fetch(%s): cache hit", ruleKey); return CacheResult.HTTP_HIT; }
From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java
/** * Create raw header - includes version, keyId, crc * // w w w .j a v a2 s . c om * @param dataCrc * @return */ public byte[] createRawHeader(long dataCrc) { try { byte[] keyId = getKeyId(); ByteArrayOutputStream header = new ByteArrayOutputStream(); header.write((byte) 100);//version header.write(ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(keyId.length).array());//key id length header.write(ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(dataCrc).array()); header.write(keyId); return header.toByteArray(); } catch (IOException ex) { Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:org.springframework.jdbc.repo.impl.jdbc.RawPropertiesRepoImplTest.java
/** * Makes sure that {@link RawPropertiesRepo#entityExists(String)} * and/or {@link RawPropertiesRepo#getProperties(String)} return * correct result for non-existing entities *///from w w w. ja v a 2 s .c o m @Test public void testGetNonExistingEntityProperties() { for (int index = 0; index < Byte.SIZE; index++) { String id = String.valueOf(Math.random()); assertFalse("Unexpected existence for ID=" + id, repo.entityExists(id)); Map<?, ?> props = repo.getProperties(id); if (ExtendedMapUtils.size(props) > 0) { fail("Unexpected proeprties for ID=" + id + ": " + props); } } }
From source file:net.ripe.rpki.commons.crypto.rfc3779.AddressFamily.java
public static AddressFamily fromDer(ASN1Encodable der) { Validate.isTrue(der instanceof DEROctetString, "DEROctetString expected"); DEROctetString derOctetString = (DEROctetString) der; byte[] bytes = derOctetString.getOctets(); Validate.isTrue(bytes.length == AFI_OCTET_COUNT_WITHOUT_SAFI || bytes.length == AFI_OCTET_COUNT_WITH_SAFI, "Byte array must consist of " + AFI_OCTET_COUNT_WITHOUT_SAFI + " or " + AFI_OCTET_COUNT_WITH_SAFI + " elements"); int thisAddressFamilyIdentifier = (unsignedByteToInt(bytes[0]) << Byte.SIZE) | unsignedByteToInt(bytes[1]); AddressFamily addressFamily;/*w ww . j ava 2 s .c o m*/ if (bytes.length == 2) { addressFamily = new AddressFamily(thisAddressFamilyIdentifier); } else { // subsequentAddressIdentifier given int thisSafi = unsignedByteToInt(bytes[2]); addressFamily = new AddressFamily(thisAddressFamilyIdentifier, thisSafi); } return addressFamily; }
From source file:com.monitor.baseservice.utils.XCodeUtil.java
/** * 1?xcode?/* w w w. j a v a2s . c o m*/ * 2?base64? * 3?????CRCCRC?8 * 4?CRC * 5??????JSON * * @param xCode * @return * @throws LogicalException */ @SuppressWarnings("unchecked") public static Map<String, Object> xDecode(String xCode) throws LogicalException { // 1 String real = xCode.substring(PREFIX_LENGTH); byte[] rst = Base64.decodeBase64(real); byte[] data = Arrays.copyOf(rst, rst.length - (Long.SIZE / Byte.SIZE)); byte[] crc = Arrays.copyOfRange(rst, data.length, rst.length); // 4 long value = byteArrayToLong(crc); byte[] realCrc = crcUnsigned(data, CRC_KEY.getBytes()); long realValue = byteArrayToLong(realCrc); if (!(value == realValue)) { System.out.println("license verify failed."); throw new LogicalException(RetStat.ERR_BAD_PARAMS, null); } xorCode(data, XOR_KEY); String info = new String(data); return JSONObject.parseObject(info, Map.class); }
From source file:net.ripe.rpki.commons.crypto.rfc3779.AddressFamily.java
public DEROctetString toDer() { int length = hasSubsequentAddressFamilyIdentifier() ? AFI_OCTET_COUNT_WITH_SAFI : AFI_OCTET_COUNT_WITHOUT_SAFI; byte[] encoded = new byte[length]; encoded[0] = (byte) (addressFamilyIdentifier >> Byte.SIZE); encoded[1] = (byte) (addressFamilyIdentifier); if (hasSubsequentAddressFamilyIdentifier()) { encoded[2] = subsequentAddressFamilyIdentifier.byteValue(); }/*w w w. j ava 2 s .c o m*/ return new DEROctetString(encoded); }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
/** * Creates a new Cryptor with the given PRNG.<br/> * <strong>DO NOT USE IN PRODUCTION</strong>. This constructor must only be used in in unit tests. Do not change method visibility. * /*ww w.j av a2 s .c o m*/ * @param prng Fast, possibly insecure PRNG. */ Aes256Cryptor(Random prng) { byte[] bytes = new byte[AES_KEY_LENGTH_IN_BITS / Byte.SIZE]; try { prng.nextBytes(bytes); this.primaryMasterKey = new SecretKeySpec(bytes, AES_KEY_ALGORITHM); prng.nextBytes(bytes); this.hMacMasterKey = new SecretKeySpec(bytes, HMAC_KEY_ALGORITHM); } finally { Arrays.fill(bytes, (byte) 0); } }