Java Code Examples for java.security.DigestException

The following examples show how to use java.security.DigestException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: besu   Source File: EthHash.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculates a dataset item and writes it to a given buffer.
 *
 * @param buffer Buffer to store dataset item in
 * @param cache EthHash Cache
 * @param index Index of the dataset item to calculate
 */
public static void calcDatasetItem(final byte[] buffer, final int[] cache, final int index) {
  final int rows = cache.length / HASH_WORDS;
  final int[] mixInts = new int[HASH_BYTES / 4];
  final int offset = index % rows * HASH_WORDS;
  mixInts[0] = cache[offset] ^ index;
  System.arraycopy(cache, offset + 1, mixInts, 1, HASH_WORDS - 1);
  intToByte(buffer, mixInts);
  final MessageDigest keccak512 = KECCAK_512.get();
  keccak512.update(buffer);
  try {
    keccak512.digest(buffer, 0, HASH_BYTES);
    ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(mixInts);
    for (int i = 0; i < DATASET_PARENTS; ++i) {
      fnvHash(
          mixInts,
          cache,
          Integer.remainderUnsigned(fnv(index ^ i, mixInts[i % 16]), rows) * HASH_WORDS);
    }
    intToByte(buffer, mixInts);
    keccak512.update(buffer);
    keccak512.digest(buffer, 0, HASH_BYTES);
  } catch (final DigestException ex) {
    throw new IllegalStateException(ex);
  }
}
 
Example 2
Source Project: android_9.0.0_r45   Source File: VerityUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a pair of {@code SharedMemory} and {@code Integer}. The {@code SharedMemory} contains
 * Merkle tree and fsverity headers for the given apk, in the form that can immediately be used
 * for fsverity setup. The data is aligned to the beginning of {@code SharedMemory}, and has
 * length equals to the returned {@code Integer}.
 */
private static Pair<SharedMemory, Integer> generateApkVerityIntoSharedMemory(
        String apkPath, byte[] expectedRootHash)
        throws IOException, SecurityException, DigestException, NoSuchAlgorithmException,
               SignatureNotFoundException {
    TrackedShmBufferFactory shmBufferFactory = new TrackedShmBufferFactory();
    byte[] generatedRootHash = ApkSignatureVerifier.generateApkVerity(apkPath,
            shmBufferFactory);
    // We only generate Merkle tree once here, so it's important to make sure the root hash
    // matches the signed one in the apk.
    if (!Arrays.equals(expectedRootHash, generatedRootHash)) {
        throw new SecurityException("Locally generated verity root hash does not match");
    }

    int contentSize = shmBufferFactory.getBufferLimit();
    SharedMemory shm = shmBufferFactory.releaseSharedMemory();
    if (shm == null) {
        throw new IllegalStateException("Failed to generate verity tree into shared memory");
    }
    if (!shm.setProtect(PROT_READ)) {
        throw new SecurityException("Failed to set up shared memory correctly");
    }
    return Pair.create(shm, contentSize);
}
 
Example 3
Source Project: android_9.0.0_r45   Source File: ByteBufferDataSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void feedIntoDataDigester(DataDigester md, long offset, int size)
        throws IOException, DigestException {
    // There's no way to tell MessageDigest to read data from ByteBuffer from a position
    // other than the buffer's current position. We thus need to change the buffer's
    // position to match the requested offset.
    //
    // In the future, it may be necessary to compute digests of multiple regions in
    // parallel. Given that digest computation is a slow operation, we enable multiple
    // such requests to be fulfilled by this instance. This is achieved by serially
    // creating a new ByteBuffer corresponding to the requested data range and then,
    // potentially concurrently, feeding these buffers into MessageDigest instances.
    ByteBuffer region;
    synchronized (mBuf) {
        mBuf.position(0);
        mBuf.limit((int) offset + size);
        mBuf.position((int) offset);
        region = mBuf.slice();
    }

    md.consume(region);
}
 
Example 4
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;
}
 
Example 5
Source Project: openjdk-jdk8u-backup   Source File: crc32.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 */
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;
}
 
Example 6
Source Project: android_9.0.0_r45   Source File: ApkVerityBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculates the fsverity root hash for integrity measurement.  This needs to be consistent to
 * what kernel returns.
 */
static byte[] generateFsverityRootHash(RandomAccessFile apk, ByteBuffer apkDigest,
        SignatureInfo signatureInfo)
        throws NoSuchAlgorithmException, DigestException, IOException {
    ByteBuffer verityBlock = ByteBuffer.allocate(CHUNK_SIZE_BYTES)
            .order(ByteOrder.LITTLE_ENDIAN);
    ByteBuffer header = slice(verityBlock, 0, FSVERITY_HEADER_SIZE_BYTES);
    ByteBuffer extensions = slice(verityBlock, FSVERITY_HEADER_SIZE_BYTES,
            CHUNK_SIZE_BYTES - FSVERITY_HEADER_SIZE_BYTES);

    calculateFsveritySignatureInternal(apk, signatureInfo, null, null, header, extensions);

    MessageDigest md = MessageDigest.getInstance(JCA_DIGEST_ALGORITHM);
    md.update(header);
    md.update(extensions);
    md.update(apkDigest);
    return md.digest();
}
 
Example 7
Source Project: openjdk-jdk9   Source File: crc32.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 */
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;
}
 
Example 8
Source Project: android_9.0.0_r45   Source File: ApkVerityBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Consumes and digests data up to BUFFER_SIZE (may continue from the previous remaining),
 * then writes the final digest to the output buffer.  Repeat until all data are consumed.
 * If the last consumption is not enough for BUFFER_SIZE, the state will stay and future
 * consumption will continuous from there.
 */
@Override
public void consume(ByteBuffer buffer) throws DigestException {
    int offset = buffer.position();
    int remaining = buffer.remaining();
    while (remaining > 0) {
        int allowance = (int) Math.min(remaining, BUFFER_SIZE - mBytesDigestedSinceReset);
        // Optimization: set the buffer limit to avoid allocating a new ByteBuffer object.
        buffer.limit(buffer.position() + allowance);
        mMd.update(buffer);
        offset += allowance;
        remaining -= allowance;
        mBytesDigestedSinceReset += allowance;

        if (mBytesDigestedSinceReset == BUFFER_SIZE) {
            mMd.digest(mDigestBuffer, 0, mDigestBuffer.length);
            mOutput.put(mDigestBuffer);
            // After digest, MessageDigest resets automatically, so no need to reset again.
            mMd.update(mSalt);
            mBytesDigestedSinceReset = 0;
        }
    }
}
 
Example 9
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("签名错误!");
    }
}
 
Example 10
Source Project: jdk8u60   Source File: crc32.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 */
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;
}
 
Example 11
Source Project: openjdk-jdk8u   Source File: DigestBase.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 12
Source Project: besu   Source File: DirectAcyclicGraphSeed.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] dagSeed(final long block) {
  final byte[] seed = new byte[32];
  if (Long.compareUnsigned(block, EPOCH_LENGTH) >= 0) {
    final MessageDigest keccak256 = KECCAK_256.get();
    for (int i = 0; i < Long.divideUnsigned(block, EPOCH_LENGTH); ++i) {
      keccak256.update(seed);
      try {
        keccak256.digest(seed, 0, seed.length);
      } catch (final DigestException ex) {
        throw new IllegalStateException(ex);
      }
    }
  }
  return seed;
}
 
Example 13
Source Project: openjsse   Source File: DigestBase.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected final byte[] engineDigest() {
    byte[] b = new byte[digestLength];
    try {
        engineDigest(b, 0, b.length);
    } catch (DigestException e) {
        throw (ProviderException)
            new ProviderException("Internal error").initCause(e);
    }
    return b;
}
 
Example 14
Source Project: android_9.0.0_r45   Source File: VerityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates Merkle tree and fsverity metadata.
 *
 * @return {@code SetupResult} that contains the {@code EsetupResultCode}, and when success, the
 *         {@code FileDescriptor} to read all the data from.
 */
public static SetupResult generateApkVeritySetupData(@NonNull String apkPath) {
    if (DEBUG) Slog.d(TAG, "Trying to install apk verity to " + apkPath);
    SharedMemory shm = null;
    try {
        byte[] signedRootHash = ApkSignatureVerifier.getVerityRootHash(apkPath);
        if (signedRootHash == null) {
            if (DEBUG) {
                Slog.d(TAG, "Skip verity tree generation since there is no root hash");
            }
            return SetupResult.skipped();
        }

        Pair<SharedMemory, Integer> result = generateApkVerityIntoSharedMemory(apkPath,
                signedRootHash);
        shm = result.first;
        int contentSize = result.second;
        FileDescriptor rfd = shm.getFileDescriptor();
        if (rfd == null || !rfd.valid()) {
            return SetupResult.failed();
        }
        return SetupResult.ok(Os.dup(rfd), contentSize);
    } catch (IOException | SecurityException | DigestException | NoSuchAlgorithmException |
            SignatureNotFoundException | ErrnoException e) {
        Slog.e(TAG, "Failed to set up apk verity: ", e);
        return SetupResult.failed();
    } finally {
        if (shm != null) {
            shm.close();
        }
    }
}
 
Example 15
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    for (byte element: data) {
        md.update(element);
    }
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
            "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 16
Source Project: android_9.0.0_r45   Source File: ApkSignatureVerifier.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates the Merkle tree and verity metadata to the buffer allocated by the {@code
 * ByteBufferFactory}.
 *
 * @return the verity root hash of the generated Merkle tree.
 */
public static byte[] generateApkVerity(String apkPath, ByteBufferFactory bufferFactory)
        throws IOException, SignatureNotFoundException, SecurityException, DigestException,
               NoSuchAlgorithmException {
    // first try v3
    try {
        return ApkSignatureSchemeV3Verifier.generateApkVerity(apkPath, bufferFactory);
    } catch (SignatureNotFoundException e) {
        // try older version
    }
    return ApkSignatureSchemeV2Verifier.generateApkVerity(apkPath, bufferFactory);
}
 
Example 17
Source Project: openjdk-jdk9   Source File: DigestBase.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected final byte[] engineDigest() {
    byte[] b = new byte[digestLength];
    try {
        engineDigest(b, 0, b.length);
    } catch (DigestException e) {
        throw (ProviderException)
            new ProviderException("Internal error").initCause(e);
    }
    return b;
}
 
Example 18
static byte[] generateFsverityRootHash(String apkPath)
        throws IOException, SignatureNotFoundException, DigestException,
               NoSuchAlgorithmException {
    try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
        SignatureInfo signatureInfo = findSignature(apk);
        VerifiedSigner vSigner = verify(apk, false);
        if (vSigner.verityRootHash == null) {
            return null;
        }
        return ApkVerityBuilder.generateFsverityRootHash(
                apk, ByteBuffer.wrap(vSigner.verityRootHash), signatureInfo);
    }
}
 
Example 19
static byte[] generateApkVerity(String apkPath, ByteBufferFactory bufferFactory)
        throws IOException, SignatureNotFoundException, SecurityException, DigestException,
               NoSuchAlgorithmException {
    try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
        SignatureInfo signatureInfo = findSignature(apk);
        return ApkSigningBlockUtils.generateApkVerity(apkPath, bufferFactory, signatureInfo);
    }
}
 
Example 20
static byte[] generateFsverityRootHash(String apkPath)
        throws NoSuchAlgorithmException, DigestException, IOException,
               SignatureNotFoundException {
    try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
        SignatureInfo signatureInfo = findSignature(apk);
        VerifiedSigner vSigner = verify(apk, false);
        if (vSigner.verityRootHash == null) {
            return null;
        }
        return ApkVerityBuilder.generateFsverityRootHash(
                apk, ByteBuffer.wrap(vSigner.verityRootHash), signatureInfo);
    }
}
 
Example 21
Source Project: android_9.0.0_r45   Source File: ApkVerityBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates fsverity metadata and the Merkle tree into the {@link ByteBuffer} created by the
 * {@link ByteBufferFactory}. The bytes layout in the buffer will be used by the kernel and is
 * ready to be appended to the target file to set up fsverity. For fsverity to work, this data
 * must be placed at the next page boundary, and the caller must add additional padding in that
 * case.
 *
 * @return ApkVerityResult containing the fsverity data and the root hash of the Merkle tree.
 */
static ApkVerityResult generateApkVerity(RandomAccessFile apk,
        SignatureInfo signatureInfo, ByteBufferFactory bufferFactory)
        throws IOException, SecurityException, NoSuchAlgorithmException, DigestException {
    long signingBlockSize =
            signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset;
    long dataSize = apk.length() - signingBlockSize;
    int[] levelOffset = calculateVerityLevelOffset(dataSize);
    int merkleTreeSize = levelOffset[levelOffset.length - 1];

    ByteBuffer output = bufferFactory.create(
            merkleTreeSize
            + CHUNK_SIZE_BYTES);  // maximum size of fsverity metadata
    output.order(ByteOrder.LITTLE_ENDIAN);

    ByteBuffer tree = slice(output, 0, merkleTreeSize);
    ByteBuffer header = slice(output, merkleTreeSize,
            merkleTreeSize + FSVERITY_HEADER_SIZE_BYTES);
    ByteBuffer extensions = slice(output, merkleTreeSize + FSVERITY_HEADER_SIZE_BYTES,
            merkleTreeSize + CHUNK_SIZE_BYTES);
    byte[] apkDigestBytes = new byte[DIGEST_SIZE_BYTES];
    ByteBuffer apkDigest = ByteBuffer.wrap(apkDigestBytes);
    apkDigest.order(ByteOrder.LITTLE_ENDIAN);

    // NB: Buffer limit is set inside once finished.
    calculateFsveritySignatureInternal(apk, signatureInfo, tree, apkDigest, header, extensions);

    // Put the reverse offset to fs-verity header at the end.
    output.position(merkleTreeSize + FSVERITY_HEADER_SIZE_BYTES + extensions.limit());
    output.putInt(FSVERITY_HEADER_SIZE_BYTES + extensions.limit()
            + 4);  // size of this integer right before EOF
    output.flip();

    return new ApkVerityResult(output, apkDigestBytes);
}
 
Example 22
Source Project: ForgeHax   Source File: MCPMappingLoader.java    License: MIT License 5 votes vote down vote up
public MCPMappingLoader(String mapping)
  throws IOException, CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException {
  String[] tokens = mapping.split("_");
  if (tokens.length < 3) {
    throw new CantLoadMCPMappingException("Invalid mapping string specified.");
  }
  
  srgDir = getSubDirForZip(tokens, baseSrgUrl, baseSrgDir);
  mappingDir = getSubDirForZip(tokens, baseMappingUrl, baseMappingDir);
  
  srgFile = new File(srgDir, "joined.srg");
  excFile = new File(srgDir, "joined.exc");
  staticMethodsFile = new File(srgDir, "static_methods.txt");
  
  if (!srgFile.exists()) {
    throw new CantLoadMCPMappingException(
      "Unable to find joined.srg. Your MCP conf folder may be corrupt.");
  }
  
  if (!excFile.exists()) {
    throw new CantLoadMCPMappingException(
      "Unable to find joined.exc. Your MCP conf folder may be corrupt.");
  }
  
  if (!staticMethodsFile.exists()) {
    throw new CantLoadMCPMappingException(
      "Unable to find static_methods.txt. Your MCP conf folder may be corrupt.");
  }
  
  staticMethods = new StaticMethodsFile(staticMethodsFile);
  excFileData = new ExcFile(excFile);
  srgFileData = new SrgFile(srgFile, excFileData, staticMethods);
  
  csvFieldData = new CsvFile(new File(mappingDir, "fields.csv"));
  csvMethodData = new CsvFile(new File(mappingDir, "methods.csv"));
  csvParamData = new ParamCsvFile(new File(mappingDir, "params.csv"));
}
 
Example 23
Source Project: openjdk-jdk9   Source File: TestSameValue.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    md.update(data);
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
                "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 24
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    for (byte element: data) {
        md.update(element);
    }
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
            "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 25
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    md.update(data);
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
            "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 26
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {

    for (int i = 0; i < data.length / 2; i++) {
        md.update(data, i * 2, 2);
    }
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
            "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 27
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    md.update(ByteBuffer.wrap(data));
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
              "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 28
Source Project: Bytecoder   Source File: DigestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected final byte[] engineDigest() {
    byte[] b = new byte[digestLength];
    try {
        engineDigest(b, 0, b.length);
    } catch (DigestException e) {
        throw (ProviderException)
            new ProviderException("Internal error").initCause(e);
    }
    return b;
}
 
Example 29
Source Project: dble   Source File: Security.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Scrambling for caching_sha2_password plugin.
 * <pre>
 * Scramble = XOR(SHA2(password), SHA2(SHA2(SHA2(password)), Nonce))
 * </pre>
 *
 * @throws DigestException
 */
public static byte[] scrambleCachingSha2(byte[] password, byte[] seed) throws DigestException {
    MessageDigest md;
    byte[] mysqlScrambleBuff = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
        byte[] dig1 = new byte[cachingSha2DigestLength];
        byte[] dig2 = new byte[cachingSha2DigestLength];
        byte[] scramble1 = new byte[cachingSha2DigestLength];

        // SHA2(src) => digest_stage1
        md.update(password, 0, password.length);
        md.digest(dig1, 0, cachingSha2DigestLength);
        md.reset();

        // SHA2(digest_stage1) => digest_stage2
        md.update(dig1, 0, dig1.length);
        md.digest(dig2, 0, cachingSha2DigestLength);
        md.reset();

        // SHA2(digest_stage2, m_rnd) => scramble_stage1
        md.update(dig2, 0, dig1.length);
        md.update(seed, 0, seed.length);
        md.digest(scramble1, 0, cachingSha2DigestLength);

        // XOR(digest_stage1, scramble_stage1) => scramble
        mysqlScrambleBuff = new byte[cachingSha2DigestLength];
        xorString(dig1, mysqlScrambleBuff, scramble1, cachingSha2DigestLength);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return mysqlScrambleBuff;
}
 
Example 30
Source Project: TencentKona-8   Source File: DigestBase.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected final byte[] engineDigest() {
    byte[] b = new byte[digestLength];
    try {
        engineDigest(b, 0, b.length);
    } catch (DigestException e) {
        throw (ProviderException)
            new ProviderException("Internal error").initCause(e);
    }
    return b;
}