public static String SHA1(String decrypt) throws DigestException { //获取信息摘要 - 参数字典排序后字符串 try { //指定sha1算法 MessageDigest digest = MessageDigest .getInstance("SHA-1"); digest.update(decrypt.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuilder hexString = new StringBuilder(); // 字节数组转换为 十六进制 数 for (byte aMessageDigest : messageDigest) { String shaHex = Integer.toHexString(aMessageDigest & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new DigestException("签名错误!"); } }
@Test public void testPull() throws IOException, RegistryException, DigestException { // Pulls the busybox image. RegistryClient registryClient = new RegistryClient(null, "localhost:5000", "busybox"); V21ManifestTemplate manifestTemplate = registryClient.pullManifest("latest", V21ManifestTemplate.class); DescriptorDigest realDigest = manifestTemplate.getLayerDigests().get(0); // Pulls a layer BLOB of the busybox image. Path destFile = temporaryFolder.newFile().toPath(); Path checkBlobFile = temporaryFolder.newFile().toPath(); Blob blob = registryClient.pullBlob(realDigest, destFile); try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(checkBlobFile))) { BlobDescriptor blobDescriptor = blob.writeTo(outputStream); Assert.assertEquals(realDigest, blobDescriptor.getDigest()); } Assert.assertArrayEquals(Files.readAllBytes(destFile), Files.readAllBytes(checkBlobFile)); }
@Test public void testPull_unknownBlob() throws RegistryException, IOException, DigestException { DescriptorDigest nonexistentDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); try { RegistryClient registryClient = new RegistryClient(null, "localhost:5000", "busybox"); registryClient.pullBlob(nonexistentDigest, Mockito.mock(Path.class)); Assert.fail("Trying to pull nonexistent blob should have errored"); } catch (RegistryErrorException ex) { Assert.assertThat( ex.getMessage(), CoreMatchers.containsString( "pull BLOB for localhost:5000/busybox with digest " + nonexistentDigest)); } }
@Test public void test_smokeTest() throws IOException, DigestException { for (Map.Entry<String, String> knownHash : knownSha256Hashes.entrySet()) { String toHash = knownHash.getKey(); String expectedHash = knownHash.getValue(); OutputStream underlyingOutputStream = new ByteArrayOutputStream(); CountingDigestOutputStream countingDigestOutputStream = new CountingDigestOutputStream(underlyingOutputStream); byte[] bytesToHash = toHash.getBytes(StandardCharsets.UTF_8); InputStream toHashInputStream = new ByteArrayInputStream(bytesToHash); ByteStreams.copy(toHashInputStream, countingDigestOutputStream); BlobDescriptor expectedBlobDescriptor = new BlobDescriptor(bytesToHash.length, DescriptorDigest.fromHash(expectedHash)); Assert.assertEquals(expectedBlobDescriptor, countingDigestOutputStream.toBlobDescriptor()); Assert.assertEquals(bytesToHash.length, countingDigestOutputStream.getTotalBytes()); } }
@Before public void setUp() throws DigestException { baseLayerBlobDescriptor = new BlobDescriptor( 631, DescriptorDigest.fromDigest( "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef")); baseLayerDiffId = DescriptorDigest.fromDigest( "sha256:b56ae66c29370df48e7377c8f9baa744a3958058a766793f821dadcb144a4647"); classesLayerBlobDescriptor = new BlobDescriptor( 223, DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad")); classesLayerDiffId = DescriptorDigest.fromDigest( "sha256:a3f3e99c29370df48e7377c8f9baa744a3958058a766793f821dadcb144a8372"); }
@Test public void testGetLayerFile() throws DigestException { DescriptorDigest layerDigest = DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"); ArgumentCaptor<String> fileNameCaptor = ArgumentCaptor.forClass(String.class); Mockito.when(mockPath.resolve(fileNameCaptor.capture())).thenReturn(mockPath); Path layerFile = CacheFiles.getLayerFile(mockPath, layerDigest); Assert.assertEquals( "8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad.tar.gz", fileNameCaptor.getValue()); Assert.assertEquals(mockPath, layerFile); }
@Test public void testToJson() throws IOException, URISyntaxException, DigestException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("json/containerconfig.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); // Creates the JSON object to serialize. ContainerConfigurationTemplate containerConfigJson = new ContainerConfigurationTemplate(); containerConfigJson.setContainerEnvironment(Arrays.asList("VAR1=VAL1", "VAR2=VAL2")); containerConfigJson.setContainerEntrypoint(Arrays.asList("some", "entrypoint", "command")); containerConfigJson.addLayerDiffId( DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad")); // Serializes the JSON object. ByteArrayOutputStream jsonStream = new ByteArrayOutputStream(); JsonTemplateMapper.writeJson(jsonStream, containerConfigJson); Assert.assertEquals(expectedJson, jsonStream.toString()); }
@Test public void testFromJson() throws IOException, URISyntaxException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("json/containerconfig.json").toURI()); // Deserializes into a manifest JSON object. ContainerConfigurationTemplate containerConfigJson = JsonTemplateMapper.readJsonFromFile(jsonFile, ContainerConfigurationTemplate.class); Assert.assertEquals( Arrays.asList("VAR1=VAL1", "VAR2=VAL2"), containerConfigJson.getContainerEnvironment()); Assert.assertEquals( Arrays.asList("some", "entrypoint", "command"), containerConfigJson.getContainerEntrypoint()); Assert.assertEquals( DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"), containerConfigJson.getLayerDiffId(0)); }
@Test public void testToJson() throws DigestException, IOException, URISyntaxException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("json/v22manifest.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); // Creates the JSON object to serialize. V22ManifestTemplate manifestJson = new V22ManifestTemplate(); manifestJson.setContainerConfiguration( 1000, DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad")); manifestJson.addLayer( 1000_000, DescriptorDigest.fromHash( "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236")); // Serializes the JSON object. ByteArrayOutputStream jsonStream = new ByteArrayOutputStream(); JsonTemplateMapper.writeJson(jsonStream, manifestJson); Assert.assertEquals(expectedJson, jsonStream.toString()); }
@Test public void testFromJson() throws IOException, URISyntaxException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("json/v22manifest.json").toURI()); // Deserializes into a manifest JSON object. V22ManifestTemplate manifestJson = JsonTemplateMapper.readJsonFromFile(jsonFile, V22ManifestTemplate.class); Assert.assertEquals( DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"), manifestJson.getContainerConfigurationDigest()); Assert.assertEquals(1000, manifestJson.getContainerConfigurationSize()); Assert.assertEquals( DescriptorDigest.fromHash( "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236"), manifestJson.getLayerDigest(0)); Assert.assertEquals(1000_000, manifestJson.getLayerSize(0)); }
@Before public void setUp() throws DigestException, LayerPropertyNotFoundException, DuplicateLayerException { Image testImage = new Image(); testImage.setEnvironmentVariable("VAR1", "VAL1"); testImage.setEnvironmentVariable("VAR2", "VAL2"); testImage.setEntrypoint(Arrays.asList("some", "entrypoint", "command")); DescriptorDigest fakeDigest = DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"); Layer fakeLayer = new ReferenceLayer(new BlobDescriptor(1000, fakeDigest), fakeDigest); testImage.addLayer(fakeLayer); imageToJsonTranslator = new ImageToJsonTranslator(testImage); }
@Test public void testFromJson() throws URISyntaxException, IOException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("json/v21manifest.json").toURI()); // Deserializes into a manifest JSON object. V21ManifestTemplate manifestJson = JsonTemplateMapper.readJsonFromFile(jsonFile, V21ManifestTemplate.class); Assert.assertEquals( DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"), manifestJson.getLayerDigest(0)); Assert.assertEquals("some v1-compatible object", manifestJson.getV1Compatibility(0)); }
@Test public void testToImage_v21() throws IOException, LayerPropertyNotFoundException, DuplicateLayerException, DigestException, URISyntaxException { // Loads the JSON string. Path jsonFile = Paths.get(getClass().getClassLoader().getResource("json/v21manifest.json").toURI()); // Deserializes into a manifest JSON object. V21ManifestTemplate manifestTemplate = JsonTemplateMapper.readJsonFromFile(jsonFile, V21ManifestTemplate.class); Image image = JsonToImageTranslator.toImage(manifestTemplate); List<Layer> layers = image.getLayers(); Assert.assertEquals(1, layers.size()); Assert.assertEquals( DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"), layers.get(0).getBlobDescriptor().getDigest()); }
protected void setLessInstances(String key, String format, String fileName, String sourceName, String sourcePath) throws InterruptedException, IOException, NoSuchAlgorithmException, DigestException { setPxInstance(key, "500", format, fileName, sourceName, sourcePath); setPxInstance(key, "400", format, fileName, sourceName, sourcePath); setPxInstance(key, "200", format, fileName, sourceName, sourcePath); }
private File getSubDirForZip(String[] tokens, String baseZipUrl, String baseSubDir) throws CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException, IOException { if (!baseDir.exists() && !baseDir.mkdirs()) throw new CantLoadMCPMappingException("Application data folder does not exist and cannot be created."); File subDir = new File(baseDir, replaceTokens(baseSubDir, tokens)); if (!subDir.exists() && !subDir.mkdirs()) throw new CantLoadMCPMappingException("Data folder does not exist and cannot be created."); try { RemoteZipHandler rzh = new RemoteZipHandler(replaceTokens(baseZipUrl, tokens), subDir, "SHA1"); rzh.checkRemoteZip(); } catch (Throwable t) { ASMStackLogger.printStackTrace(t); } return subDir; }
/** */ protected int engineDigest(byte[] buf, int offset, int len) throws DigestException { byte[] result = new byte[CRC32_LENGTH]; result = int2quad(seed); if (len < CRC32_LENGTH) { throw new DigestException("partial digests not returned"); } if (buf.length - offset < CRC32_LENGTH) { throw new DigestException("insufficient space in the output " + "buffer to store the digest"); } System.arraycopy(result, 0, buf, offset, CRC32_LENGTH); //processBuffer(buffer, 0, bufferIndex, result, 0); /*if (len < CRC32_LENGTH) { throw new DigestException("partial digests not returned"); } if (buf.length - offset < CRC32_LENGTH) { throw new DigestException("insufficient space in the output " + "buffer to store the digest"); } System.arraycopy(result, 0, buf, offset, CRC32_LENGTH); */ init(); return CRC32_LENGTH; }
protected final int engineDigest(byte[] out, int ofs, int len) throws DigestException { if (len < digestLength) { throw new DigestException("Length must be at least " + digestLength + " for " + algorithm + "digests"); } if ((ofs < 0) || (len < 0) || (ofs > out.length - len)) { throw new DigestException("Buffer too short to store digest"); } if (bytesProcessed < 0) { engineReset(); } implDigest(out, ofs); bytesProcessed = -1; return digestLength; }
/** * A hash-based derivation function defined in NIST SP 800-90Ar1 10.3.1. * The function is used inside Hash_DRBG, and can also be used as an * approved conditioning function as described in 800-90B 6.4.2.2. * * @param digest a {@code MessageDigest} object in reset state * @param outLen {@link MessageDigest#getDigestLength} of {@code digest} * @param requested requested output length, in bytes * @param inputs input data * @return the condensed/expanded output */ public static byte[] hashDf(MessageDigest digest, int outLen, int requested, byte[]... inputs) { int len = (requested + outLen - 1) / outLen; byte[] temp = new byte[len * outLen]; int counter = 1; for (int i=0; i<len; i++) { digest.update((byte) counter); digest.update((byte)(requested >> 21)); // requested*8 as int32 digest.update((byte)(requested >> 13)); digest.update((byte)(requested >> 5)); digest.update((byte)(requested << 3)); for (byte[] input : inputs) { digest.update(input); } try { digest.digest(temp, i * outLen, outLen); } catch (DigestException e) { throw new AssertionError("will not happen", e); } counter++; } return temp.length == requested? temp: Arrays.copyOf(temp, requested); }
public void run() throws DigestException { System.err.println(home + " starting"); synchronized (this) { state = -1; } while (bag.size > 0) { while (bag.size > 0) { for (int n = 500; (n > 0) && (bag.size > 0); --n) { bag.expand(md); } distribute(); } steal(); } synchronized (this) { state = -2; } distribute(); lifelinesteal(); System.err.println(home + " stopping"); }
private void digest(MessageDigest md, int d) throws DigestException { if (size >= depth.length) { grow(); } ++count; final int offset = size * 20; md.digest(hash, offset, 20); final int v = ((0x7f & hash[offset + 16]) << 24) | ((0xff & hash[offset + 17]) << 16) | ((0xff & hash[offset + 18]) << 8) | (0xff & hash[offset + 19]); final int n = (int) (Math.log(1.0 - v / 2147483648.0) / den); if (n > 0) { if (d > 1) { depth[size] = d - 1; lower[size] = 0; upper[size++] = n; } else { count += n; } } }
public void expand(MessageDigest md) throws DigestException { final int top = size - 1; final int d = depth[top]; final int l = lower[top]; final int u = upper[top] - 1; if (u == l) { size = top; } else { upper[top] = u; } final int offset = top * 20; hash[offset + 20] = (byte) (u >> 24); hash[offset + 21] = (byte) (u >> 16); hash[offset + 22] = (byte) (u >> 8); hash[offset + 23] = (byte) u; md.update(hash, offset, 24); digest(md, d); }
@Override protected int engineDigest(byte[] buf, int offset, int len) throws DigestException { if (len < 32) throw new DigestException("Invalid digest length for SHA256"); if (posn <= (64 - 9)) { block[posn] = (byte)0x80; Arrays.fill(block, posn + 1, 64 - 8, (byte)0); } else { block[posn] = (byte)0x80; Arrays.fill(block, posn + 1, 64, (byte)0); transform(block, 0); Arrays.fill(block, 0, 64 - 8, (byte)0); } writeBE32(block, 64 - 8, (int)(length >> 32)); writeBE32(block, 64 - 4, (int)length); transform(block, 0); posn = 0; for (int index = 0; index < 8; ++index) writeBE32(buf, offset + index * 4, h[index]); return 32; }
@Override protected int engineDigest(byte[] buf, int offset, int len) throws DigestException { if (len < 64) throw new DigestException("Invalid digest length for BLAKE2b"); Arrays.fill(block, posn, 128, (byte)0); transform(-1); for (int index = 0; index < 8; ++index) { long value = h[index]; buf[offset++] = (byte)value; buf[offset++] = (byte)(value >> 8); buf[offset++] = (byte)(value >> 16); buf[offset++] = (byte)(value >> 24); buf[offset++] = (byte)(value >> 32); buf[offset++] = (byte)(value >> 40); buf[offset++] = (byte)(value >> 48); buf[offset++] = (byte)(value >> 56); } return 32; }
@Override protected int engineDigest(byte[] buf, int offset, int len) throws DigestException { if (len < 32) throw new DigestException("Invalid digest length for BLAKE2s"); Arrays.fill(block, posn, 64, (byte)0); transform(-1); for (int index = 0; index < 8; ++index) { int value = h[index]; buf[offset++] = (byte)value; buf[offset++] = (byte)(value >> 8); buf[offset++] = (byte)(value >> 16); buf[offset++] = (byte)(value >> 24); } return 32; }
@Override protected int engineDigest(byte[] buf, int offset, int len) throws DigestException { if (len < 64) throw new DigestException("Invalid digest length for SHA512"); if (posn <= (128 - 17)) { block[posn] = (byte)0x80; Arrays.fill(block, posn + 1, 128 - 8, (byte)0); } else { block[posn] = (byte)0x80; Arrays.fill(block, posn + 1, 128, (byte)0); transform(block, 0); Arrays.fill(block, 0, 128 - 8, (byte)0); } writeBE64(block, 128 - 8, length); transform(block, 0); posn = 0; for (int index = 0; index < 8; ++index) writeBE64(buf, offset + index * 8, h[index]); return 64; }
/** * Test using resource data. * <p> * Format: SHA-256 digest | LZFSE encoded data * <p> * lzfse.test: contains bvx-, bvx1, bvx2, bvxn encrypted random words (text) * * @throws IOException * @throws java.security.NoSuchAlgorithmException * @throws java.security.DigestException */ @Test public void defaultTest() throws IOException, NoSuchAlgorithmException, DigestException { InputStream is = this.getClass().getClassLoader().getResourceAsStream("lzfse.test"); assertNotNull("lzfse.test", is); byte[] digest = new byte[32]; is.read(digest); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream dis = new LZFSEInputStream(is)) { copy(dis, baos, buffer); } MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] _digest = md.digest(baos.toByteArray()); assertArrayEquals("SHA-256", digest, _digest); }
private Cipher getCipher(int cipherMode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DigestException { Cipher cipher = Cipher.getInstance(this.cipherTransformation); // calculate a file specific IV based on the unique relative filename byte[] iv = new byte[cipher.getBlockSize()]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(this.relativeFilename.getBytes()); md.digest(iv, 0, cipher.getBlockSize()); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); // load the mode, symmetric key and IV into the Cipher cipher.init(cipherMode, this.secretKeySpec, ivParameterSpec); return cipher; }
/** * Generating private key. Source: https://cr.yp.to/ecdh.html * * @param randomBytes random bytes (32+ bytes) * @return generated private key */ public static byte[] keyGenPrivate(byte[] randomBytes) throws NoSuchAlgorithmException, DigestException { if (randomBytes.length < 32) { throw new RuntimeException("Random bytes too small"); } // Hashing Random Bytes instead of using random bytes directly // Just in case as reference ed255519 implementation do same MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.digest(randomBytes, 0, randomBytes.length); byte[] privateKey = digest.digest(); // Performing bit's flipping privateKey[0] &= 248; privateKey[31] &= 127; privateKey[31] |= 64; return privateKey; }
public static void main(String[] args) throws DigestException, NoSuchAlgorithmException, IOException { SecureRandom secureRandom = new SecureRandom(); if (!new File("keys").exists()) { new File("keys").mkdir(); } for (int i = 0; i < 4; i++) { File pubFile = new File("keys/actor-key-" + i + ".pub"); File keyFile = new File("keys/actor-key-" + i + ".key"); if (pubFile.exists() && keyFile.exists()) { System.out.println("Key #" + i + " exists. Skipping..."); continue; } Curve25519KeyPair keyPair = Curve25519.keyGen(secureRandom.generateSeed(64)); FileUtils.writeByteArrayToFile(pubFile, keyPair.getPublicKey()); FileUtils.writeByteArrayToFile(keyFile, keyPair.getPrivateKey()); } System.out.println("Shared Secret: " + Base64.getEncoder().encodeToString(secureRandom.generateSeed(64))); }