org.bouncycastle.util.Arrays Java Examples

The following examples show how to use org.bouncycastle.util.Arrays. 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 File: GCMDataB.java    From InflatableDonkey with MIT License 7 votes vote down vote up
public static byte[] decrypt(byte[] key, byte[] data) {
    // TODO utilize GCMAES#decrypt method
    try {
        if (data.length < NONCE_LENGTH + TAG_LENGTH) {
            throw new IllegalArgumentException("data packet too short");
        }

        int cipherTextLength = data.length - NONCE_LENGTH - TAG_LENGTH;

        byte[] nonce = Arrays.copyOf(data, NONCE_LENGTH);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        AEADParameters parameters = new AEADParameters(new KeyParameter(key), TAG_LENGTH * 8, nonce);
        cipher.init(false, parameters);

        byte[] out = new byte[cipher.getOutputSize(cipherTextLength + TAG_LENGTH)];

        int pos = cipher.processBytes(data, NONCE_LENGTH, data.length - NONCE_LENGTH, out, 0);
        pos += cipher.doFinal(out, pos);

        return Arrays.copyOf(out, pos);

    } catch (IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example #2
Source File: SM2PreprocessSigner.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
protected BigInteger[] derDecode(byte[] encoding)
        throws IOException {
    ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoding));
    if (seq.size() != 2) {
        return null;
    }

    BigInteger r = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
    BigInteger s = ASN1Integer.getInstance(seq.getObjectAt(1)).getValue();

    byte[] expectedEncoding = derEncode(r, s);
    if (!Arrays.constantTimeAreEqual(expectedEncoding, encoding)) {
        return null;
    }

    return new BigInteger[]{r, s};
}
 
Example #3
Source File: KeyBag.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public KeyBag(
        KeyBagID keyBagID,
        KeyBagType type,
        Map<Integer, byte[]> publicKeys,
        Map<Integer, byte[]> privateKeys) {

    this.keyBagID = Objects.requireNonNull(keyBagID);
    this.type = Objects.requireNonNull(type, "type");
    this.publicKeys = publicKeys.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    bs -> Arrays.copyOf(bs.getValue(), bs.getValue().length)));
    this.privateKeys = privateKeys.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    u -> Arrays.copyOf(u.getValue(), u.getValue().length)));
}
 
Example #4
Source File: Algorithm5.java    From sambox with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] computePassword(EncryptionContext context)
{
    context.security.encryption.revision.requireAtLeast(StandardSecurityHandlerRevision.R3,
            "Algorithm 5 requires a security handler of revision 3 or greater");
    digest.reset();
    digest.update(ENCRYPT_PADDING);
    byte[] encrypted = engine.encryptBytes(
            Arrays.copyOf(digest.digest(context.documentId()), 16), context.key());
    byte[] iterationKey = new byte[context.key().length];
    for (int i = 1; i < 20; i++)
    {
        iterationKey = Arrays.copyOf(context.key(), context.key().length);
        for (int j = 0; j < iterationKey.length; j++)
        {
            iterationKey[j] = (byte) (iterationKey[j] ^ (byte) i);
        }
        encrypted = engine.encryptBytes(encrypted, iterationKey);
    }
    return Arrays.concatenate(Arrays.copyOf(encrypted, 16), Arrays.copyOf(ENCRYPT_PADDING, 16));
}
 
Example #5
Source File: Script.java    From bushido-java-core with GNU General Public License v3.0 6 votes vote down vote up
public boolean equals(Script script) {
    if (chunks.size() != script.chunks.size()) {
        return false;
    }
    for (int i = 0; i < chunks.size(); i++) {
        if (chunks.get(i).bytes != null && script.chunks.get(i).bytes == null) {
            return false;
        }
        if (chunks.get(i).opcode.value != script.chunks.get(i).opcode.value) {
            return false;
        }
        if (Arrays.areEqual(chunks.get(i).bytes, script.chunks.get(i).bytes) == false) {
            return false;
        }
    }
    return true;
}
 
Example #6
Source File: ExtendedKey.java    From bushido-java-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructing a derived key
 *
 * @param keyHash - Derived key hash
 * @param compressed - Indicates if public key is compressed for EC calculations
 * @param sequence - Derivation sequence
 * @param depth - Derivation depth
 * @param parentFingerprint - Parent key fingerprint
 * @param ecKey - Parent ECKey
 */
public ExtendedKey(byte[] keyHash, boolean compressed, int sequence, int depth, int parentFingerprint, ECKey ecKey) {

    //key hash left side, private key base
    byte[] l = Arrays.copyOfRange(keyHash, 0, 32);
    //key hash right side, chaincode
    byte[] r = Arrays.copyOfRange(keyHash, 32, 64);
    //r is chainCode bytes
    this.chainCode = r;
    this.sequence = sequence;
    this.depth = depth;
    this.parentFingerprint = parentFingerprint;

    if (ecKey != null) {
        this.ecKey = new ECKey(l, ecKey);
    } else {
        this.ecKey = new ECKey(l, compressed);
    }
}
 
Example #7
Source File: EnvelopeHelper.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 构造交易信封
 *
 * @param originalProposal
 * @param identity
 * @param endorserResponses
 * @return
 * @throws ValidateException
 * @throws InvalidProtocolBufferException
 * @throws NodeException
 */
public static Common.Envelope buildTxEnvelope(ProposalPackage.Proposal originalProposal, ISigningIdentity
        identity, ProposalResponsePackage.ProposalResponse... endorserResponses) throws ValidateException,
        InvalidProtocolBufferException, NodeException {
    ProposalVO proposalVO = new ProposalVO();
    proposalVO.parseFrom(originalProposal);

    //签名头部的消息创建者字段应与身份一致
    if (Arrays.compareUnsigned(proposalVO.getHeaderVO().getSignatureHeader().getCreator().toByteArray(), identity
            .getIdentity().serialize()) != 0) {
        throw new ValidateException("Wrong signatureHeader creator");
    }

    TransactionPackage.Transaction transaction = TransactionHelper.buildSingleTransaction(proposalVO.getPayloadVO
            ().toProto(), identity, endorserResponses);

    Common.Payload.Builder payloadBuilder = Common.Payload.newBuilder();
    Common.Header header = Common.Header.parseFrom(originalProposal.getHeader());
    payloadBuilder.setHeader(header);
    payloadBuilder.setData(transaction.toByteString());
    Common.Payload payload = payloadBuilder.build();

    return buildEnvelope(payload, identity);
}
 
Example #8
Source File: EthereumIESEncryptionEngine.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
public byte[] processBlock(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {

    // Compute the common value and convert to byte array.
    agree.init(privParam);
    BigInteger z = agree.calculateAgreement(pubParam);
    byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

    // Create input to KDF.
    if (V.length != 0) {
      byte[] VZ = Arrays.concatenate(V, Z);
      Arrays.fill(Z, (byte) 0);
      Z = VZ;
    }

    try {
      // Initialise the KDF.
      KDFParameters kdfParam = new KDFParameters(Z, param.getDerivationV());
      kdf.init(kdfParam);

      return forEncryption ? encryptBlock(in, inOff, inLen) : decryptBlock(in, inOff, inLen);
    } finally {
      Arrays.fill(Z, (byte) 0);
    }
  }
 
Example #9
Source File: Blake2bfMessageDigest.java    From besu with Apache License 2.0 5 votes vote down vote up
/** Reset the digest back to it's initial state. */
@Override
public void reset() {
  bufferPos = 0;
  Arrays.fill(buffer, (byte) 0);
  Arrays.fill(h, 0);
  Arrays.fill(m, (byte) 0);
  Arrays.fill(t, 0);
  f = false;
  rounds = 12;
  Arrays.fill(v, 0);
}
 
Example #10
Source File: ObliviousTransferResponse.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    ObliviousTransferResponse that = (ObliviousTransferResponse) o;
    return Objects.equals(b, that.b) &&
            java.util.Arrays.deepEquals(c, that.c) &&
            Objects.equals(d, that.d);
}
 
Example #11
Source File: ConcatenatingAESEngineTest.java    From sambox with Apache License 2.0 5 votes vote down vote up
@Test
public void encryptBytes()
{
    byte[] key = new byte[] { -40, -23, -118, -66, -77, -34, 42, 9, 11, 22, 105, 86, -92, 23,
            57, 4 };
    byte[] iv = new byte[] { 18, -87, 49, -32, -126, 116, -128, -36, -78, 70, 99, -98, -65, 90,
            -95, 101 };
    byte[] expected = new byte[] { -125, -84, -39, -13, -125, 92, 23, -82, 68, 81, -78, 105, 34,
            21, -70, -14 };
    assertArrayEquals(Arrays.concatenate(iv, expected),
            victim.encryptBytes("ChuckNorris".getBytes(), key, iv));
}
 
Example #12
Source File: ChapterIVKmehrResponseWithTimeStampInfo.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public TimeStampResponse getTimeStampResponse() {
   try {
      return new TimeStampResponse(Arrays.clone(this.timeStampBytes));
   } catch (TSPException var2) {
      LOG.error(var2.getClass().getSimpleName() + ":" + var2.getMessage(), var2);
   } catch (IOException var3) {
      LOG.error(var3.getClass().getSimpleName() + ":" + var3.getMessage(), var3);
   }

   return null;
}
 
Example #13
Source File: ECKey.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean equals(Object obj) {

    if (obj instanceof ECKey) {
        return Arrays.areEqual(((ECKey) obj).getPrivate(), this.getPrivate())
                && Arrays.areEqual(((ECKey) obj).getPublic(), this.getPublic())
                && Arrays.areEqual(((ECKey) obj).getPublicKeyHash(), this.getPublicKeyHash())
                && ((ECKey) obj).isCompressed() == this.isCompressed();

    }
    return false;
}
 
Example #14
Source File: ChunkKeys.java    From InflatableDonkey with MIT License 5 votes vote down vote up
Optional<byte[]> type2(byte[] chunkEncryptionKey, byte[] keyEncryptionKey) {
    if (chunkEncryptionKey.length != 0x19) {
        logger.warn("-- type2() - bad chunk encryption key length: 0x:{}", Hex.toHexString(chunkEncryptionKey));
        return Optional.empty();
    }
    byte[] wrappedKey = Arrays.copyOfRange(chunkEncryptionKey, 0x01, 0x19);
    return RFC3394Wrap.unwrapAES(keyEncryptionKey, wrappedKey)
            .map(u -> {
                byte[] k = new byte[0x11];
                k[0] = 0x01;
                System.arraycopy(u, 0, k, 1, u.length);
                return k;
            });
}
 
Example #15
Source File: ECPublicKey.java    From bop-bitcoin-client with Apache License 2.0 5 votes vote down vote up
@Override
public ECPublicKey clone () throws CloneNotSupportedException
{
	ECPublicKey c = (ECPublicKey) super.clone ();
	c.pub = Arrays.clone (pub);
	return c;
}
 
Example #16
Source File: Document.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public final byte[] getContent() throws UnsealConnectorException {
   if (this.content == null && this.expection != null) {
      throw this.expection;
   } else {
      return Arrays.clone(this.content);
   }
}
 
Example #17
Source File: BuilderUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void checkHash(byte[] blobHashValue, byte[] decompressedBlob) throws InvalidBlobContentConnectorException, TechnicalConnectorException {
   try {
      byte[] calculatedHashValue = buildHash(decompressedBlob);
      if (!Arrays.areEqual(blobHashValue, calculatedHashValue)) {
         String blobHashAsString = blobHashValue != null ? new String(Base64.encode(blobHashValue)) : "";
         String calculatedHashAsString = calculatedHashValue != null ? new String(Base64.encode(calculatedHashValue)) : "";
         throw new InvalidBlobContentConnectorException(InvalidBlobContentConnectorExceptionValues.HASH_VALUES_DIFFERENT, (Blob)null, decompressedBlob, new Object[]{blobHashAsString, calculatedHashAsString});
      }
   } catch (NoSuchAlgorithmException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #18
Source File: HashTreeRootTest.java    From cava with Apache License 2.0 5 votes vote down vote up
@Test
void list2() {
  byte[] _1s = new byte[32];
  byte[] _2s = new byte[32];
  byte[] _3s = new byte[32];
  byte[] _4s = new byte[32];
  byte[] _5s = new byte[32];
  byte[] _6s = new byte[32];
  byte[] _7s = new byte[32];
  byte[] _8s = new byte[32];
  byte[] _9s = new byte[32];
  byte[] _as = new byte[32];
  Arrays.fill(_1s, (byte) 1);
  Arrays.fill(_2s, (byte) 2);
  Arrays.fill(_3s, (byte) 3);
  Arrays.fill(_4s, (byte) 4);
  Arrays.fill(_5s, (byte) 5);
  Arrays.fill(_6s, (byte) 6);
  Arrays.fill(_7s, (byte) 7);
  Arrays.fill(_8s, (byte) 8);
  Arrays.fill(_9s, (byte) 9);
  Arrays.fill(_as, (byte) 10);

  assertEquals(
      Bytes.fromHexString("0x55DC6699E7B5713DD9102224C302996F931836C6DAE9A4EC6AB49C966F394685"),
      SSZ.hashTreeRoot(
          Bytes.wrap(_1s),
          Bytes.wrap(_2s),
          Bytes.wrap(_3s),
          Bytes.wrap(_4s),
          Bytes.wrap(_5s),
          Bytes.wrap(_6s),
          Bytes.wrap(_7s),
          Bytes.wrap(_8s),
          Bytes.wrap(_9s),
          Bytes.wrap(_as)));
}
 
Example #19
Source File: Document.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public final byte[] getContent() throws UnsealConnectorException {
   if (this.content == null && this.expection != null) {
      throw this.expection;
   } else {
      return Arrays.clone(this.content);
   }
}
 
Example #20
Source File: CablePairingData.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
/**
 * @param cableData
 * @param sessionKeyPair
 * @return
 */
public static CablePairingData generatePairingData(CableRegistrationData cableData,
    KeyPair sessionKeyPair) {
  byte[] sharedSecret = Crypto.getS(sessionKeyPair.getPrivate(), cableData.publicKey);

  byte[] info = "FIDO caBLE v1 pairing data".getBytes(StandardCharsets.US_ASCII);
  byte[] version = ByteBuffer.allocate(4).putInt(cableData.versions.get(0)).array();

  byte[] result = Crypto.hkdfSha256(sharedSecret, Crypto.sha256Digest(Bytes.concat(version,
      Crypto.compressECPublicKey((ECPublicKey) sessionKeyPair.getPublic()), cableData.publicKey)),
      info, HKDF_SHA_LENGTH);

  return new CablePairingData(cableData.versions.get(0), Arrays.copyOf(result, K_LENGTH),
      Arrays.copyOfRange(result, K_LENGTH, 2 * K_LENGTH));
}
 
Example #21
Source File: ComplianceToolModeAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldGenerateARequestToALocalHubService() {
    Response authnRequest = client
            .target(appUri("generate-request"))
            .request()
            .post(json(null));

    RequestResponseBody authnSaml = authnRequest.readEntity(RequestResponseBody.class);

    assertThat(authnSaml.getSsoLocation()).isEqualTo(URI.create(COMPLIANCE_TOOL_HOST + "/SAML2/SSO"));
    String responseFor = complianceTool.createResponseFor(authnSaml.getSamlRequest(), VERIFIED_USER_ON_SERVICE_WITH_NON_MATCH_SETTING_ID);

    Map<String, String> translateResponseRequestData = ImmutableMap.of(
            "samlResponse", responseFor,
            "requestId", authnSaml.getRequestId(),
            "levelOfAssurance", LevelOfAssurance.LEVEL_1.name());

    Response response = client
            .target(appUri("translate-response"))
            .request()
            .post(json(translateResponseRequestData));

    assertThat(response.getStatus()).isEqualTo(200);

    JSONObject jsonResponse = new JSONObject(response.readEntity(String.class));

    JSONObject attributes = jsonResponse.getJSONObject("attributes");
    assertThat(attributes.keySet()).containsExactlyInAnyOrder(Arrays.append(COMMON_FIELDS, "gender"));

    checkMatchingDatasetMatches(attributes, matchingDataset);
}
 
Example #22
Source File: ChapterIVKmehrResponseWithTimeStampInfo.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public TimeStampResponse getTimeStampResponse() {
   try {
      return new TimeStampResponse(Arrays.clone(this.timeStampBytes));
   } catch (TSPException var2) {
      LOG.error(var2.getClass().getSimpleName() + ":" + var2.getMessage(), var2);
   } catch (IOException var3) {
      LOG.error(var3.getClass().getSimpleName() + ":" + var3.getMessage(), var3);
   }

   return null;
}
 
Example #23
Source File: ECPublicKey.java    From WalletCordova with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ECPublicKey clone () throws CloneNotSupportedException
{
	ECPublicKey c = (ECPublicKey) super.clone ();
	c.pub = Arrays.clone (pub);
	return c;
}
 
Example #24
Source File: Address.java    From bop-bitcoin-client with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals (Object obj)
{
	if ( this == obj )
	{
		return true;
	}
	if ( obj == null || getClass () != obj.getClass () )
	{
		return false;
	}
	return Arrays.areEqual (bytes, ((Address) obj).bytes) && type == ((Address) obj).type;
}
 
Example #25
Source File: NativeECPublicKey.java    From ECTester with MIT License 5 votes vote down vote up
public Mscng(int flag, byte[] meta, byte[] header, byte[] x, byte[] y, ECParameterSpec params) {
    super(ByteUtil.concatenate(new byte[]{0x04}, x, y), params);
    this.flag = flag;
    this.meta = Arrays.clone(meta);
    this.header = Arrays.clone(header);
    this.x = Arrays.clone(x);
    this.y = Arrays.clone(y);
}
 
Example #26
Source File: ChapterIVKmehrResponseWithTimeStampInfo.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public TimeStampResponse getTimeStampResponse() {
   try {
      return new TimeStampResponse(Arrays.clone(this.timeStampBytes));
   } catch (TSPException var2) {
      LOG.error(var2.getClass().getSimpleName() + ":" + var2.getMessage(), var2);
   } catch (IOException var3) {
      LOG.error(var3.getClass().getSimpleName() + ":" + var3.getMessage(), var3);
   }

   return null;
}
 
Example #27
Source File: Document.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public final byte[] getContent() throws UnsealConnectorException {
   if (this.content == null && this.expection != null) {
      throw this.expection;
   } else {
      return Arrays.clone(this.content);
   }
}
 
Example #28
Source File: tls_sigature.java    From tls-sig-api-java with MIT License 4 votes vote down vote up
public static CheckTLSSignatureResult CheckTLSSignatureEx(
        String sig,
        long sdkappid,
        String identifier,
        String publicKey) throws DataFormatException {

    CheckTLSSignatureResult result = new CheckTLSSignatureResult();
    Security.addProvider(new BouncyCastleProvider());

    byte [] compressBytes = base64_url.base64DecodeUrl(sig.getBytes(Charset.forName("UTF-8")));

    //Decompression
    Inflater decompression =  new Inflater();
    decompression.setInput(compressBytes, 0, compressBytes.length);
    byte[] decompressBytes = new byte[1024];
    int decompressLength = decompression.inflate(decompressBytes);
    decompression.end();

    String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));

    //Get TLS.Sig from json
    JSONObject jsonObject= new JSONObject(jsonString);
    String sigTLS = jsonObject.getString("TLS.sig");

    //debase64 TLS.Sig to get serailString
    byte[] signatureBytes = Base64.decode(sigTLS.getBytes(Charset.forName("UTF-8")));

    try {
        String strSdkappid = jsonObject.getString("TLS.sdk_appid");
        String sigTime = jsonObject.getString("TLS.time");
        String sigExpire = jsonObject.getString("TLS.expire_after");

        if (Integer.parseInt(strSdkappid) != sdkappid)
        {
            result.errMessage = new String(	"sdkappid "
                    + strSdkappid
                    + " in tls sig not equal sdkappid "
                    + sdkappid
                    + " in request");
            return result;
        }

        if ( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
            result.errMessage = new String("TLS sig is out of date");
            return result;
        }

        //Get Serial String from json
        String SerialString = "TLS.appid_at_3rd:" + 0 + "\n"
                + "TLS.account_type:" + 0 + "\n"
                + "TLS.identifier:" + identifier + "\n"
                + "TLS.sdk_appid:" + sdkappid + "\n"
                + "TLS.time:" + sigTime + "\n"
                + "TLS.expire_after:" + sigExpire + "\n";

        Reader reader = new CharArrayReader(publicKey.toCharArray());
        PEMParser  parser = new PEMParser(reader);
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object obj = parser.readObject();
        parser.close();
        PublicKey pubKeyStruct  = converter.getPublicKey((SubjectPublicKeyInfo) obj);

        Signature signature = Signature.getInstance("SHA256withECDSA","BC");
        signature.initVerify(pubKeyStruct);
        signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
        boolean bool = signature.verify(signatureBytes);
        result.expireTime = Integer.parseInt(sigExpire);
        result.initTime = Integer.parseInt(sigTime);
        result.verifyResult = bool;
    }
    catch(Exception e)
    {
        e.printStackTrace();
        result.errMessage = "Failed in checking sig";
    }

    return result;
}
 
Example #29
Source File: NtlmContext.java    From jcifs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void verifyMIC ( byte[] data, byte[] mic ) throws CIFSException {
    byte[] sk = this.verifyKey;
    if ( sk == null ) {
        throw new CIFSException("Signing is not initialized");
    }

    int ver = SMBUtil.readInt4(mic, 0);
    if ( ver != 1 ) {
        throw new SmbUnsupportedOperationException("Invalid signature version");
    }

    MessageDigest mac = Crypto.getHMACT64(sk);
    int seq = SMBUtil.readInt4(mic, 12);
    mac.update(mic, 12, 4); // sequence
    byte[] dgst = mac.digest(data); // data
    byte[] trunc = Arrays.copyOf(dgst, 8);

    if ( log.isDebugEnabled() ) {
        log.debug("Digest " + Hexdump.toHexString(dgst));
        log.debug("Truncated " + Hexdump.toHexString(trunc));
    }

    boolean encrypted = ( this.ntlmsspFlags & NtlmFlags.NTLMSSP_NEGOTIATE_KEY_EXCH ) != 0;
    if ( encrypted ) {
        try {
            trunc = this.sealServerHandle.doFinal(trunc);
            if ( log.isDebugEnabled() ) {
                log.debug("Decrypted " + Hexdump.toHexString(trunc));
            }
        }
        catch ( GeneralSecurityException e ) {
            throw new CIFSException("Failed to decrypt MIC", e);
        }
    }

    int expectSeq = this.verifySequence.getAndIncrement();
    if ( expectSeq != seq ) {
        throw new CIFSException(String.format("Invalid MIC sequence, expect %d have %d", expectSeq, seq));
    }

    byte[] verify = new byte[8];
    System.arraycopy(mic, 4, verify, 0, 8);
    if ( !MessageDigest.isEqual(trunc, verify) ) {
        if ( log.isDebugEnabled() ) {
            log.debug(String.format("Seq = %d ver = %d encrypted = %s", seq, ver, encrypted));
            log.debug(String.format("Expected MIC %s != %s", Hexdump.toHexString(trunc), Hexdump.toHexString(verify)));
        }
        throw new CIFSException("Invalid MIC");
    }

}
 
Example #30
Source File: AbstractStoresTest.java    From alfresco-simple-content-stores with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether the content in two files matches.
 *
 * @param fileA
 *            the first of the two files
 * @param fileB
 *            the second of the two files
 * @return {@code true} if the files match, {@code false} otherwise
 */
protected static boolean contentMatches(final Path fileA, final Path fileB) throws IOException
{
    boolean matches;

    try (InputStream isA = Files.newInputStream(fileA))
    {
        try (InputStream isB = Files.newInputStream(fileB))
        {
            final byte[] buffA = new byte[4096];
            final byte[] buffB = new byte[4096];
            int offset = 0;

            matches = true;
            while (matches)
            {
                final int bytesReadA = isA.read(buffA);
                final int bytesReadB = isB.read(buffB);

                if (bytesReadA != bytesReadB)
                {
                    matches = false;
                    if (!matches)
                    {
                        LOGGER.debug(
                                "contentMatches failed due to difference in length - read {} expected vs {} bytes in slice starting at position {}",
                                bytesReadA, bytesReadB, offset);
                    }
                }
                else if (bytesReadA != -1)
                {
                    // note: don't have to care about equals check including bytes between bytesRead and length
                    // (any left over bytes from previous read would be identical in both buffers)
                    matches = Arrays.areEqual(buffA, buffB);

                    if (!matches)
                    {
                        LOGGER.debug(
                                "contentMatches failed due to difference in content slice starting at position {} and with a length of {}",
                                offset, bytesReadA);
                    }

                    offset += bytesReadA;
                }
                else
                {
                    break;
                }
            }
        }
    }
    return matches;
}