Java Code Examples for org.bouncycastle.util.Arrays#copyOfRange()

The following examples show how to use org.bouncycastle.util.Arrays#copyOfRange() . 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: 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 2
Source File: Substring.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] perform(byte[] input) throws Exception {
	
	int start = (int) startSpinner.getValue();
	int end = (int) endSpinner.getValue();
	
	if( start < 0 ) 
		start = input.length + start;
	if( end < 0 )
		end = input.length + end;
	if( end > input.length )
		end = input.length + 1;
	
	byte[] slice = Arrays.copyOfRange(input, start, end);
	return slice;
}
 
Example 3
Source File: HttpMethodExtractor.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] perform(byte[] input) throws Exception {
	try {
		IBurpExtenderCallbacks callbacks = BurpUtils.getInstance().getCallbacks();
		IExtensionHelpers helpers = callbacks.getHelpers();
		int length = input.length;
		
		int methodEnd = helpers.indexOf(input, " ".getBytes(), false, 0, length);
		byte[] result = Arrays.copyOfRange(input, 0, methodEnd);
		
		return result;
		
	} catch (Exception e) {
		throw new IllegalArgumentException("Provided input is not a valid http request.");
	}
}
 
Example 4
Source File: ReadWriteTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
static void verifyRandom ( int bufSize, long length, boolean expectEof, InputStream is ) throws IOException {
    long start = System.currentTimeMillis();
    byte buffer[] = new byte[bufSize];
    long p = 0;
    Random r = getRandom();
    while ( p < length ) {

        int rs = Math.min(bufSize, (int) ( length - p ));
        int read = is.read(buffer, 0, rs);
        if ( read < 0 ) {
            fail("Unexpected EOF at " + p);
        }

        byte verify[] = new byte[read];
        randBytes(r, verify);
        byte actual[] = Arrays.copyOfRange(buffer, 0, read);

        assertArrayEquals("Data matches at offset " + p, actual, verify);

        p += read;
    }
    if ( expectEof ) {
        assertEquals("Expecting EOF", -1, is.read(buffer, 0, 1));
    }
    log.debug("Read " + length + " took " + ( System.currentTimeMillis() - start ));
}
 
Example 5
Source File: ReadWriteTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
static void verifyRandom ( int bufSize, long length, boolean expectEof, InputStream is ) throws IOException {
    long start = System.currentTimeMillis();
    byte buffer[] = new byte[bufSize];
    long p = 0;
    Random r = getRandom();
    while ( p < length ) {

        int rs = Math.min(bufSize, (int) ( length - p ));
        int read = is.read(buffer, 0, rs);
        if ( read < 0 ) {
            fail("Unexpected EOF at " + p);
        }

        byte verify[] = new byte[read];
        randBytes(r, verify);
        byte actual[] = Arrays.copyOfRange(buffer, 0, read);

        assertArrayEquals("Data matches at offset " + p, actual, verify);

        p += read;
    }
    if ( expectEof ) {
        assertEquals("Expecting EOF", -1, is.read(buffer, 0, 1));
    }
    log.debug("Read " + length + " took " + ( System.currentTimeMillis() - start ));
}
 
Example 6
Source File: Base64Url.java    From wakeup-qcloud-sdk with Apache License 2.0 5 votes vote down vote up
public static byte[] base64EncodeUrl(byte[] in_str) {
	byte[] out_str = new byte[1024];

	int out_current = 0;
	int current = 0;
	int length = in_str.length;

	while (length > 2) { /* keep going until we have less than 24 bits */

		out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current]) >>> 2))];
		out_str[out_current++] = base64_table_url[unsignedToBytes(unsignedToBytes(unsignedToBytes(in_str[current]) & 0x03) << 4)
				+ unsignedToBytes((unsignedToBytes(in_str[current + 1]) >>> 4))];
		out_str[out_current++] = base64_table_url[(unsignedToBytes((unsignedToBytes(in_str[current + 1]) & 0x0f)) << 2)
				+ unsignedToBytes((unsignedToBytes(in_str[current + 2]) >>> 6))];
		out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current + 2]) & 0x3f))];
		current += 3;
		length -= 3; /* we just handle 3 octets of data */
	}

	/* now deal with the tail end of things */
	if (length != 0) {
		out_str[out_current++] = base64_table_url[unsignedToBytes(in_str[current]) >>> 2];
		if (length > 1) {
			out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current]) & 0x03) << 4)
					+ unsignedToBytes(unsignedToBytes(in_str[current + 1]) >>> 4)];
			out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current + 1]) & 0x0f) << 2)];
			out_str[out_current++] = base64_pad_url;
		} else {
			out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current]) & 0x03) << 4)];
			out_str[out_current++] = base64_pad_url;
			out_str[out_current++] = base64_pad_url;
		}
	}

	// System.out.println("length in base64EncodeUrl: " + out_current );
	byte[] out_bytes = new String(out_str).getBytes();
	return Arrays.copyOfRange(out_bytes, 0, out_current);
}
 
Example 7
Source File: ExtendedKey.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public static ExtendedKey parse(String serialized, boolean compressed) throws Exception {
    byte[] data = ByteUtil.fromBase58WithChecksum(serialized);
    if (data.length != 78)
    {
        throw new Exception("Invalid extended key");
    }
    byte[] type = Arrays.copyOf(data, 4);
    boolean hasPrivate;
    if (Arrays.areEqual(type, xprv))
    {
        hasPrivate = true;
    }
    else if (Arrays.areEqual(type, xpub))
    {
        hasPrivate = false;
    }
    else
    {
        throw new Exception("Invalid or unsupported key type");
    }
    int depth = data[4] & 0xff;
    int parentFingerprint = data[5] & 0xff;
    parentFingerprint <<= 8;
    parentFingerprint |= data[6] & 0xff;
    parentFingerprint <<= 8;
    parentFingerprint |= data[7] & 0xff;
    parentFingerprint <<= 8;
    parentFingerprint |= data[8] & 0xff;
    int sequence = data[9] & 0xff;
    sequence <<= 8;
    sequence |= data[10] & 0xff;
    sequence <<= 8;
    sequence |= data[11] & 0xff;
    sequence <<= 8;
    sequence |= data[12] & 0xff;
    final byte[] chainCode = Arrays.copyOfRange(data, 13, 13 + 32);
    final byte[] keyBytes = Arrays.copyOfRange(data, 13 + 32, data.length);
    final ECKey ecKey = new ECKey(keyBytes, compressed, hasPrivate);
    return new ExtendedKey(chainCode, sequence, depth, parentFingerprint, ecKey);
}
 
Example 8
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 9
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 10
Source File: FakedHttpWrapper.java    From AgentX with Apache License 2.0 5 votes vote down vote up
public byte[] unwrapFromResponse(final byte[] bytes) {
    // caution: placeholder bytes' end-pos must less than 200
    String fuzzyHeader = new String(Arrays.copyOfRange(bytes, 0, 200));
    if (!fuzzyHeader.startsWith(Http.VERSION_1_1)) {
        throw new RuntimeException("unknown format");
    }
    fuzzyHeader = fuzzyHeader.substring(fuzzyHeader.indexOf("Content-Length: ") + "Content-Length: ".length());
    fuzzyHeader = fuzzyHeader.substring(0, fuzzyHeader.indexOf(Http.CRLF));
    int rawLen = Integer.parseInt(fuzzyHeader);
    return Arrays.copyOfRange(bytes, bytes.length - rawLen, bytes.length);
}
 
Example 11
Source File: SplitAndSelect.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected byte[] perform(byte[] input) throws Exception {

	byte[] delimmiter = delim.getBytes();

	int itemNumber = 0;
	try {
		String itemValue = item.getText();
		itemNumber = Integer.valueOf(itemValue);
	} catch(Exception e) {
		return input;
	}

	if( itemNumber < 0 )
		return input;

	IBurpExtenderCallbacks cbs = BurpUtils.getInstance().getCallbacks();
	IExtensionHelpers helpers = cbs.getHelpers();
	int length = input.length;

	int start = 0;
	int offset = 0;
	int counter = 0;
	while( counter < itemNumber ) {
		offset = helpers.indexOf(input, delimmiter, false, start, length);
		if( offset >= 0 ) {
			start = offset + delimmiter.length;
			counter++;
		} else {
			break;
		}
	}

	int end = helpers.indexOf(input, delimmiter, false, start, length);
	if( end < 0 )
		end = length;

	byte[] result = Arrays.copyOfRange(input, start, end);
	return result;
}
 
Example 12
Source File: TPMClockInfo.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static TPMClockInfo unmarshal(byte[] bytes){
    int pos = 0;
    long clock = Marshal.stream64ToLong(Arrays.copyOfRange(bytes, pos, pos+TPMConstants.SIZEOFLONG));
    pos += TPMConstants.SIZEOFLONG;
    int resetCount = Marshal.stream32ToInt(Arrays.copyOfRange(bytes, pos, pos+TPMConstants.SIZEOFINT));
    pos += TPMConstants.SIZEOFINT;
    int restartCount = Marshal.stream32ToInt(Arrays.copyOfRange(bytes, pos, pos + TPMConstants.SIZEOFINT));
    pos += TPMConstants.SIZEOFINT;
    byte safe = Arrays.copyOfRange(bytes, pos, pos + TPMConstants.SIZEOFBYTE)[0];
    pos += TPMConstants.SIZEOFBYTE;
    return new TPMClockInfo(clock, resetCount, restartCount, safe);
}
 
Example 13
Source File: EthereumIESEncryptionEngine.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
private byte[] decryptBlock(byte[] in_enc, int inOff, int inLen) throws InvalidCipherTextException {
  byte[] M, K, K1, K2;
  int len = 0;

  // Ensure that the length of the input is greater than the MAC in bytes
  if (inLen < V.length + mac.getMacSize()) {
    throw new InvalidCipherTextException("Length of input must be greater than the MAC and V combined");
  }

  // note order is important: set up keys, do simple encryptions, check mac, do final encryption.

  // Block cipher mode.
  K1 = new byte[((IESWithCipherParameters) param).getCipherKeySize() / 8];
  K2 = new byte[param.getMacKeySize() / 8];
  K = new byte[K1.length + K2.length];

  kdf.generateBytes(K, 0, K.length);
  System.arraycopy(K, 0, K1, 0, K1.length);
  System.arraycopy(K, K1.length, K2, 0, K2.length);

  CipherParameters cp = new KeyParameter(K1);

  // If IV provide use it to initialize the cipher
  if (IV != null) {
    cp = new ParametersWithIV(cp, IV);
  }

  cipher.init(false, cp);

  M = new byte[cipher.getOutputSize(inLen - V.length - mac.getMacSize())];

  // do initial processing
  len = cipher.processBytes(in_enc, inOff + V.length, inLen - V.length - mac.getMacSize(), M, 0);


  // Convert the length of the encoding vector into a byte array.
  byte[] P2 = param.getEncodingV();
  byte[] L2 = null;
  if (V.length != 0) {
    L2 = getLengthTag(P2);
  }

  // Verify the MAC.
  int end = inOff + inLen;
  byte[] T1 = Arrays.copyOfRange(in_enc, end - mac.getMacSize(), end);

  byte[] T2 = new byte[T1.length];
  // Ethereum change:
  // Instead of initializing the mac with the bytes, we initialize with the hash of the bytes.
  // Old code: mac.init(new KeyParameter(K2));
  Digest hash = new SHA256Digest();
  byte[] K2hash = new byte[hash.getDigestSize()];
  hash.reset();
  hash.update(K2, 0, K2.length);
  hash.doFinal(K2hash, 0);
  mac.init(new KeyParameter(K2hash));
  // we also update the mac with the IV:
  mac.update(IV, 0, IV.length);
  // end of Ethereum change.

  mac.update(in_enc, inOff + V.length, inLen - V.length - T2.length);

  if (P2 != null) {
    mac.update(P2, 0, P2.length);
  }
  if (V.length != 0) {
    mac.update(L2, 0, L2.length);
  }
  mac.update(commonMac, 0, commonMac.length);
  mac.doFinal(T2, 0);

  if (!Arrays.constantTimeAreEqual(T1, T2)) {
    throw new InvalidCipherTextException("invalid MAC");
  }

  if (cipher == null) {
    return M;
  } else {
    len += cipher.doFinal(M, len);

    return Arrays.copyOfRange(M, 0, len);
  }
}
 
Example 14
Source File: Base64Url.java    From wakeup-qcloud-sdk with Apache License 2.0 4 votes vote down vote up
public static byte[] base64DecodeUrl(byte[] in_str) {
	// const unsigned char *current = in_str;
	int ch, i = 0, j = 0, k;
	int current = 0;
	byte[] out_str = new byte[1024];
	int length = in_str.length;
	/* this sucks for threaded environments */

	/* run through the whole string, converting as we go */
	// while ((ch = in_str[current++]) != '\0' && length-- > 0) {
	ch = in_str[0];
	while (length-- > 0) {
		ch = in_str[current++];
		if (ch == base64_pad_url)
			break;
		/*
		 * When Base64 gets POSTed, all pluses are interpreted as spaces.
		 * This line changes them back. It's not exactly the Base64 spec,
		 * but it is completely compatible with it (the spec says that
		 * spaces are invalid). This will also save many people considerable
		 * headache. - Turadg Aleahmad <[email protected]>
		 */
		if (ch == ' ')
			ch = '*'; // never using '+'

		ch = base64_reverse_table_url[ch];
		if (ch < 0)
			continue;

		switch (i % 4) {
		case 0:
			out_str[j] = (byte) unsignedToBytes(unsignedToBytes(ch) << 2);
			break;
		case 1:
			out_str[j++] |= (byte) unsignedToBytes(unsignedToBytes(ch) >>> 4);
			out_str[j] = (byte) unsignedToBytes(unsignedToBytes(unsignedToBytes(ch) & 0x0f) << 4);
			break;
		case 2:
			out_str[j++] |= (byte) unsignedToBytes(unsignedToBytes(ch) >>> 2);
			out_str[j] = (byte) unsignedToBytes(unsignedToBytes(unsignedToBytes(ch) & 0x03) << 6);
			break;
		case 3:
			out_str[j++] |= (byte) unsignedToBytes(ch);
			break;
		}
		i++;
	}
	k = j;
	/* mop things up if we ended on a boundary */
	if (ch == base64_pad_url) {
		switch (i % 4) {
		case 0:
		case 1:
			byte[] error = new byte[1];
			error[0] = '\0';
			return error;
		case 2:
			k++;
		case 3:
			out_str[k++] = 0;
		}
	}
	return Arrays.copyOfRange(out_str, 0, j);
}
 
Example 15
Source File: DefaultQCloudClient.java    From wakeup-qcloud-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyUserSig(String identifier, String sig)throws QCloudException {
	try {
		Security.addProvider(new BouncyCastleProvider());
		
		//DeBaseUrl64 urlSig to json
		Base64 decoder = new Base64();

		byte [] compressBytes = Base64Url.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= JSON.parseObject(jsonString);
		String sigTLS = jsonObject.getString("TLS.sig");
		
		//debase64 TLS.Sig to get serailString
		byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
		
		String strSdkAppid = jsonObject.getString("TLS.sdk_appid");
		String sigTime = jsonObject.getString("TLS.time");
		String sigExpire = jsonObject.getString("TLS.expire_after");
		
		if (!imConfig.getSdkAppId().equals(strSdkAppid))
		{
			return false;
		}

		if ( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
			return false;
		}
		
		//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:" + imConfig.getSdkAppId() + "\n" + 
			"TLS.time:" + sigTime + "\n" + 
			"TLS.expire_after:" + sigExpire + "\n";
	
        Reader reader = new CharArrayReader(imConfig.getPublicKey().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")));
		return signature.verify(signatureBytes);
	}catch (Exception e) {
		throw new QCloudException(e);
	}
}
 
Example 16
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 17
Source File: ExtendedKey.java    From bop-bitcoin-client with Apache License 2.0 4 votes vote down vote up
public static ExtendedKey parse (String serialized) throws ValidationException
{
	byte[] data = ByteUtils.fromBase58WithChecksum (serialized);
	if ( data.length != 78 )
	{
		throw new ValidationException ("invalid extended key");
	}
	byte[] type = Arrays.copyOf (data, 4);
	boolean hasPrivate;
	if ( Arrays.areEqual (type, xprv) || Arrays.areEqual (type, tprv) )
	{
		hasPrivate = true;
	}
	else if ( Arrays.areEqual (type, xpub) || Arrays.areEqual (type, tpub) )
	{
		hasPrivate = false;
	}
	else
	{
		throw new ValidationException ("invalid magic number for an extended key");
	}

	int depth = data[4] & 0xff;

	int parent = data[5] & 0xff;
	parent <<= 8;
	parent |= data[6] & 0xff;
	parent <<= 8;
	parent |= data[7] & 0xff;
	parent <<= 8;
	parent |= data[8] & 0xff;

	int sequence = data[9] & 0xff;
	sequence <<= 8;
	sequence |= data[10] & 0xff;
	sequence <<= 8;
	sequence |= data[11] & 0xff;
	sequence <<= 8;
	sequence |= data[12] & 0xff;

	byte[] chainCode = Arrays.copyOfRange (data, 13, 13 + 32);
	byte[] pubOrPriv = Arrays.copyOfRange (data, 13 + 32, data.length);
	Key key;
	if ( hasPrivate )
	{
		key = new ECKeyPair (new BigInteger (1, pubOrPriv), true);
	}
	else
	{
		key = new ECPublicKey (pubOrPriv, true);
	}
	return new ExtendedKey (key, chainCode, depth, parent, sequence);
}
 
Example 18
Source File: LineExtractor.java    From cstc with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected byte[] perform(byte[] input) throws Exception {

	int lineNumber = 0;
	try {
		String number = lineNumberField.getText();
		lineNumber = Integer.valueOf(number);
	} catch(Exception e) {
		return input;
	}

	if( lineNumber <= 0 )
		return input;

	byte[] lineEndings = "\r\n".getBytes();
	switch ((String) this.formatBox.getSelectedItem()) {
	case "\\r\\n":
		lineEndings = "\r\n".getBytes();
		break;
	case "\\r":
		lineEndings = "\r".getBytes();
		break;
	case "\\n":
		lineEndings = "\n".getBytes();
		break;
	}

	IBurpExtenderCallbacks callbacks = BurpUtils.getInstance().getCallbacks();
	IExtensionHelpers helpers = callbacks.getHelpers();
	int length = input.length;

	int start = 0;
	int offset = 0;
	int counter = 0;
	while( counter < lineNumber - 1 ) {
		offset = helpers.indexOf(input, lineEndings, false, start, length);
		if( offset >= 0 ) {
			start = offset + lineEndings.length;
			counter++;
		} else {
			break;
		}
	}

	int end = helpers.indexOf(input, lineEndings, false, start, length);
	if( end < 0 )
		end = length;

	byte[] result = Arrays.copyOfRange(input, start, end);
	return result;
}
 
Example 19
Source File: ECIESEncryptionEngine.java    From besu with Apache License 2.0 4 votes vote down vote up
private byte[] decrypt(
    final byte[] inEnc, final int inOff, final int inLen, final byte[] commonMac)
    throws InvalidCipherTextException {
  final byte[] M;
  final byte[] K;
  final byte[] K1;
  final byte[] K2;

  int len;

  // Ensure that the length of the input is greater than the MAC in bytes
  if (inLen <= (CIPHER_MAC_KEY_SIZE / 8)) {
    throw new InvalidCipherTextException("Length of input must be greater than the MAC");
  }

  // Block cipher mode.
  K1 = new byte[CIPHER_KEY_SIZE / 8];
  K2 = new byte[CIPHER_MAC_KEY_SIZE / 8];
  K = new byte[K1.length + K2.length];

  kdf.generateBytes(K, 0, K.length);
  System.arraycopy(K, 0, K1, 0, K1.length);
  System.arraycopy(K, K1.length, K2, 0, K2.length);

  // Use IV to initialize cipher.
  cipher.init(false, new ParametersWithIV(new KeyParameter(K1), iv));

  M = new byte[cipher.getOutputSize(inLen - mac.getMacSize())];
  len = cipher.processBytes(inEnc, inOff, inLen - mac.getMacSize(), M, 0);
  len += cipher.doFinal(M, len);

  // Convert the length of the encoding vector into a byte array.
  final byte[] P2 = PARAM.getEncodingV();

  // Verify the MAC.
  final int end = inOff + inLen;
  final byte[] T1 = Arrays.copyOfRange(inEnc, end - mac.getMacSize(), end);
  final byte[] T2 = new byte[T1.length];

  final byte[] K2hash = new byte[hash.getDigestSize()];
  hash.reset();
  hash.update(K2, 0, K2.length);
  hash.doFinal(K2hash, 0);

  mac.init(new KeyParameter(K2hash));
  mac.update(iv, 0, iv.length);
  mac.update(inEnc, inOff, inLen - T2.length);

  if (P2 != null) {
    mac.update(P2, 0, P2.length);
  }

  if (commonMac != null) {
    mac.update(commonMac, 0, commonMac.length);
  }

  mac.doFinal(T2, 0);

  if (!Arrays.constantTimeAreEqual(T1, T2)) {
    throw new InvalidCipherTextException("Invalid MAC.");
  }

  // Output the message.
  return Arrays.copyOfRange(M, 0, len);
}
 
Example 20
Source File: BtcAddressUtils.java    From blockchain-java with Apache License 2.0 2 votes vote down vote up
/**
 * 生成公钥的校验码
 *
 * @param payload
 * @return
 */
public static byte[] checksum(byte[] payload) {
    return Arrays.copyOfRange(doubleHash(payload), 0, 4);
}