GVKun编程网logo

计算字节数组的SHA-1(计算数组所占字节数)

24

对于计算字节数组的SHA-1感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解计算数组所占字节数,并且为您提供关于16进制字符串和字节数组的互转、byte字节数组的压缩、c#–从字节数组中读取

对于计算字节数组的SHA-1感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解计算数组所占字节数,并且为您提供关于16进制字符串和字节数组的互转、byte字节数组的压缩、c# – 从字节数组中读取行(不将字节数组转换为字符串)、c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数的宝贵知识。

本文目录一览:

计算字节数组的SHA-1(计算数组所占字节数)

计算字节数组的SHA-1(计算数组所占字节数)

我正在寻找一种以Java字节数组作为消息获取SHA-1校验和的方法。

我应该使用第三方工具还是JVM内置的某些工具可以帮助您?

答案1

小编典典

关于什么:

import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.Formatter;public static String SHAsum(byte[] convertme) throws NoSuchAlgorithmException{    MessageDigest md = MessageDigest.getInstance("SHA-1");     return byteArray2Hex(md.digest(convertme));}private static String byteArray2Hex(final byte[] hash) {    Formatter formatter = new Formatter();    for (byte b : hash) {        formatter.format("%02x", b);    }    return formatter.toString();}

16进制字符串和字节数组的互转

16进制字符串和字节数组的互转

/**

*16进制字符串转为字节数组

*/

public byte[] hexToByte(String hex){

  /**

  *先去掉16进制字符串的空格

  */

  hex = hex.replace(" ","");

  /**

  *字节数组长度为16进制字符串长度的一半

  */

  int byteLength = hex.length()/2;

  byte[] bytes = new byte[byteLength];

  int m = 0;

  int n = 0;

  for(int i = 0; i<byteLength;i++){

    m = i*2+1;

    n = m+1;

    int intHex = Integer.decode("0x"+hex.substring(i * 2, m) + hex.substring(m, n));

    bytes[i] = Byte.valueOf((byte) intVal);

  }

  return bytes;

}

/**

*字节数组转为16进制字符串

*/

public static String byteToHex(byte[] bytes) {
  String strHex = "";
  StringBuilder stringBuilder = new StringBuilder();
  for (int n = 0; n < bytes.length; n++) {
    strHex = Integer.toHexString(bytes[n] & 0xFF);
    stringBuilder.append((strHex.length() == 1) ? "0" + strHex : strHex);
  }
  return stringBuilder.toString().trim();
}

 

/**

*字符串转为16进制字符串

*/

public String str2HexStr(String str) {
  char[] chars = "0123456789ABCDEF".toCharArray();
  StringBuilder sb = new StringBuilder("");
  byte[] bs = str.getBytes();
  int bit;
  for (int i = 0; i < bs.length; i++) {
    bit = (bs[i] & 0x0f0) >> 4;
    sb.append(chars[bit]);
    bit = bs[i] & 0x0f;
    sb.append(chars[bit]);
  }
  return sb.toString().trim();
}

byte字节数组的压缩

byte字节数组的压缩

写入内容到文件

public static void writeBytesToFile() throws IOException{
        String s = "aaaaaaaaD等等";
        byte[] bs= s.getBytes();
        OutputStream out = new FileOutputStream("d:/abc.txt");
        InputStream is = new ByteArrayInputStream(bs);
        byte[] buff = new byte[1024];
        int len = 0;
        while((len=is.read(buff))!=-1){
            out.write(buff, 0, len);
        }
        is.close();
        out.close();
    }

 

 

 

gzip压缩byte[]

 

byte[] b = null;
            ByteArrayInputStream bis = new ByteArrayInputStream(byteIn);
            GZIPInputStream gzip = new GZIPInputStream(bis);
            byte[] buf = new byte[1024];
            int num = -1;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((num = gzip.read(buf, 0, buf.length)) != -1) {
            baos.write(buf, 0, num);
            }
            b = baos.toByteArray();
            baos.flush();
            baos.close();
            gzip.close();
            bis.close();

zip压缩byte[]

byte[] b = null;
ByteArrayInputStream bis = new ByteArrayInputStream(byteIn);
               ZipInputStream zip = new ZipInputStream(bis);
               ZipEntry nextEntry = zip.getNextEntry();
               while (zip.getNextEntry() != null) {
                   byte[] buf = new byte[1024];
                   int num = -1;
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   while ((num = zip.read(buf, 0, buf.length)) != -1) {
                      baos.write(buf, 0, num);
                   }
                   b = baos.toByteArray();
                   baos.flush();
                   baos.close();
               }
               zip.close();
               bis.close();

根据byte数组,生成txt文件 

 

package com.hou.test1;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class Test4 {
    public static void main(String[] args) {
        byte[] b = "123abvc到达".getBytes();
        String filePath="d:";
        String fileName=new Date().getTime()+".txt";
        getFile(b,filePath,fileName);
        System.out.println("压缩成功");
    }
    
    /** 
     * 根据byte数组,生成文件 
     */  
    public static void getFile(byte[] bfile, String filePath,String fileName) {  
        BufferedOutputStream bos = null;  
        FileOutputStream fos = null;  
        File file = null;  
        try {  
            File dir = new File(filePath);  
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在  
                dir.mkdirs();  
            }  
            file = new File(filePath+"\\"+fileName);  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(bfile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
        }  
    } 
}

根据byte数组,生成zip文件 

public static void main(String[] args) {
        byte[] b = "123abvc到达".getBytes();
        getFile1(b);
        System.out.println("压缩成功");
    }
    
    /** 
     * 根据byte数组,生成文件 
     */  
    public static void  getFile1(byte[] byteIn){
        try {
            File zipFile=new File("d:/COMPLETE"+new Date().getTime()+".zip");
            FileOutputStream zipOut;
            //以上是将创造一个zip格式的文件
            zipOut = new FileOutputStream(zipFile);
            ZipOutputStream zip=new ZipOutputStream(zipOut);
            ZipEntry zipEntry1=new ZipEntry(new Date().getTime()+"");
            zip.putNextEntry(zipEntry1);
            byte [] byte_s="测试内容aaa".getBytes();
//            zip.write(byte_s,0,byte_s.length);
            zip.write(byteIn,0,byteIn.length);
            zip.close();
            zipOut.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

 HttpGet 获取字节数组压缩成zip,.tar.gz文件

HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("authorization", head);
        httpGet.addHeader("Transfer-Encoding", "GZIP");

        try {
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            byte[] byteIn = EntityUtils.toByteArray(response.getEntity());
            
            CommonUtils.getFileFromBytes(byteIn, "QUNAR_ONE_COMMON_PRYPAY_"+System.currentTimeMillis() , ".tar.gz");
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
}

/**
     * 二进制流转换成文件
     * 
     * @param byteArray
     *            请求二进制流数据
     * @param prefix
     *            文件名前缀
     * @param suffix
     *            文件名后缀
     * @return zip压缩文件
     */
    public static File getFileFromBytes(byte[] byteArray, String prefix,String suffix) {
        BufferedOutputStream stream = null;
        File file = null;
        String str="";
        try {
            file = new File(FILE_PATH+prefix+suffix);
            file.createNewFile();// 创建临时文件
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(byteArray);
        } catch (Exception e) {
            logger.error("创建临时文件失败!"+e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    logger.error(e1);
                }
            }
        }
        
        logger.info("创建临时文件"+file.getPath()+"  "+str);
        return file;
    }

 

c# – 从字节数组中读取行(不将字节数组转换为字符串)

c# – 从字节数组中读取行(不将字节数组转换为字符串)

我有一个字节数组,我正在从NetworkStream中读取.前两个字节表示后面的数据包的长度,然后将数据包读入该长度的字节数组.我需要从NetworkStream / byte数组中读取的数据有几个字符串,即由新行字符终止的可变长度数据,以及一些固定宽度字段,如字节和长整数.所以,像这样:
// I would have delimited these for clarity but I didn't want
// to imply that the stream was delimited because it's not.
StringbyteStringStringbytebytebytelonglongbytelonglong

我知道(并且有一些说法)正在发生的数据包的格式,我需要做的是读取每个字符串值的“行”,但读取字节和长度的固定字节数.到目前为止,我提出的解决方案是使用while循环将字节读入临时字节数组,直到有换行符.然后,将字节转换为字符串.这对我来说似乎很尴尬,但我没有看到另一种显而易见的方式.我意识到我可以使用StreamReader.ReadLine(),但这将涉及另一个流,我已经有了一个NetworkStream.但如果这是更好的解决方案,我会试一试.

我考虑的另一个选项是让我的后端团队为那些String值的长度写一个或两个字节,这样我就可以读取长度,然后根据指定的长度读取字符串.

所以,正如你所看到的,我有一些选择如何解决这个问题,我希望你的意见是关于你认为最好的方法.这是我现在用于以字符串形式读取整个数据包的代码.下一步是打破数据包的各个字段,并根据数据包中的数据完成需要完成的实际编程工作,创建对象,更新UI等.

string line = null;  
while (stream.DataAvailable)
{  
    //Get the packet length;  
    UInt16 packetLength = 0;  
    header = new byte[2];  
    stream.Read(header,2);  
    // Need to reverse the header array for BitConverter class if architecture is little endian.  
    if (BitConverter.IsLittleEndian)
        Array.Reverse(header);  
    packetLength = BitConverter.ToUInt16(header,0);

    buffer = new byte[packetLength];
    stream.Read(buffer,BitConverter.ToUInt16(header,0));
    line = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
    Console.WriteLine(line);
}

解决方法

就我个人而言

>将Int16放在开头
字符串,所以你知道多久
他们会成为,而且
>使用IO.BinaryReader类
读书,它会“读”,整理,
字符串,字符等变为变量,例如BinReader.ReadInt16()将读取两个字节,返回它们代表的int16,并在流中移动两个字节

希望这可以帮助.

附:使用ReadString方法时要小心,它假定字符串前面有自定义的7位整数,即它是由BinaryWriter类编写的.
以下是这篇CodeGuru的帖子

The BinaryWriter class has two methods
for writing strings: the overloaded
Write() method and the WriteString()
method. The former writes the string
as a stream of bytes according to the
encoding the class is using. The
WriteString() method also uses the
specified encoding,but it prefixes
the string’s stream of bytes with the
actual length of the string. Such
prefixed strings are read back in via
BinaryReader.ReadString().

The interesting thing about the length value it that as few bytes as possible are used to hold this size,it is stored as a type called a 7-bit encoded integer. If the length fits in 7 bits a single byte is used,if it is greater than this then the high bit on the first byte is set and a second byte is created by shifting the value by 7 bits. This is repeated with successive bytes until there are enough bytes to hold the value. This mechanism is used to make sure that the length does not become a significant portion of the size taken up by the serialized string. BinaryWriter and BinaryReader have methods to read and write 7-bit encoded integers,but they are protected and so you can use them only if you derive from these classes.

c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数

c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数

我试图计算在另一个字节序列中字节序列发生的所有时间.但是,如果已经计算了它们,则无法重复使用字节.例如给定字符串
k.k.k.k.k.k.假设字节序列是k.k,那么它只会发现3次而不是5次,因为它们会像以下那样被分解:[k.k].[k.k].[k.k].并不喜欢[k.[k].[k].[k].[k] .k]他们在一圈并且基本上只是向右移动2.

理想情况下,我们的想法是了解压缩字典或运行时编码的外观.所以目标就是获得

k.k.k.k.k.k.只有2个部分,因为(k.k.k.)是你可以拥有的最大和最好的符号.

到目前为止这是源:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;


    static class Compression 
    {
        static int Main(string[] args)
        {

            List<byte> bytes = File.ReadAllBytes("ok.txt").ToList();
            List<List<int>> list = new List<List<int>>();

            // Starting Numbers of bytes - This can be changed manually.
            int StartingNumBytes = bytes.Count;
            for (int i = StartingNumBytes; i > 0; i--)
            {
                Console.WriteLine("i: " + i);

                for (int ii = 0; ii < bytes.Count - i; ii++)
                {
                    Console.WriteLine("ii: " + i);
                    // New pattern comes with refresh data.
                    List<byte> pattern = new List<byte>();

                    for (int iii = 0; iii < i; iii++)
                    {
                        pattern.Add(bytes[ii + iii]);
                    }



                    displayBinary(bytes,"red");
                    displayBinary(pattern,"green");

                    int matches = 0;
                   // foreach (var position in bytes.ToArray().Locate(pattern.ToArray()))
                    for (int position = 0; position < bytes.Count; position++) {
                        if (pattern.Count > (bytes.Count - position))
                        {
                            continue;
                        }


                        for (int iiii = 0; iiii < pattern.Count; iiii++)
                        {
                            if (bytes[position + iiii] != pattern[iiii])
                            {
                                //Have to use goto because C# doesn't support continue <level>
                                goto outer;
                            }

                        }

                        // If it made it this far,it has found a match.
                        matches++;
                        Console.WriteLine("Matches: " + matches + " Orig Count: " + bytes.Count + " POS: " + position);
                        if (matches > 1)
                        {
                            int numBytesToRemove = pattern.Count;
                            for (int ra = 0; ra < numBytesToRemove; ra++)
                            {
                                // Remove it at the position it was found at,once it
                                // deletes the first one,the list will shift left and you'll need to be here again.
                                bytes.RemoveAt(position);
                            }
                            displayBinary(bytes,"red");
                            Console.WriteLine(pattern.Count + " Bytes removed.");

                            // Since you deleted some bytes,set the position less because you will need to redo the pos.
                            position = position - 1;
                        }


                        outer:
                            continue;
                    }

                    List<int> sublist = new List<int>();
                    sublist.Add(matches);
                    sublist.Add(pattern.Count);
                    // Some sort of calculation to determine how good the symbol was
                    sublist.Add(bytes.Count-((matches * pattern.Count)-matches));
                    list.Add(sublist);

                }

            }



            display(list);
            Console.Read();
            return 0;
        }


        static void displayBinary(List<byte> bytes,string color="white")
        {
            switch(color){
                case "green":
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;
                case "red":
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                default:
                    break;
            }


            for (int i=0; i<bytes.Count; i++)
            {
                if (i % 8 ==0)
                    Console.WriteLine();
                Console.Write(GetIntBinaryString(bytes[i]) + " ");
            }
            Console.WriteLine();
            Console.ResetColor();
        }
        static string GetIntBinaryString(int n)
        {
            char[] b = new char[8];
            int pos = 7;
            int i = 0;

            while (i < 8)
            {
                if ((n & (1 << i)) != 0)
                {
                    b[pos] = '1';
                }
                else
                {
                    b[pos] = '0';
                }
                pos--;
                i++;
            }
            //return new string(b).Trimstart('0');
            return new string(b);
        }

        static void display(List<List<int>> list)
        {
            //
            // display everything in the List.
            //
            Console.WriteLine("Elements:");
            foreach (var sublist in list)
            {
                foreach (var value in sublist)
                {
                    Console.Write("{0,4}",value);

                }
                Console.WriteLine();
            }

            //
            // display total count.
            //
            int count = 0;
            foreach (var sublist in list)
            {
                count += sublist.Count;
            }
            Console.WriteLine("Count:");
            Console.WriteLine(count);
        }

        static public int SearchBytePattern(byte[] pattern,byte[] bytes)
        {
            int matches = 0;
            // precomputing this shaves some seconds from the loop execution
            int maxloop = bytes.Length - pattern.Length;
            for (int i = 0; i < maxloop; i++)
            {
                if (pattern[0] == bytes[i])
                {
                    bool ismatch = true;
                    for (int j = 1; j < pattern.Length; j++)
                    {
                        if (bytes[i + j] != pattern[j])
                        {
                            ismatch = false;
                            break;
                        }
                    }
                    if (ismatch)
                    {
                        matches++;
                        i += pattern.Length - 1;
                    }
                }
            }
            return matches;
        }
    }

请参考帖子获取文件的非二进制文件,这里是二进制数据:
011010110010111001101011001011100110101100101110011010110010111001101011001011100110101100101110我希望它比它的起点小.

解决方法

private static int CountOccurences(byte[] target,byte[] pattern)
{
    var targetString = BitConverter.ToString(target);
    var patternString = BitConverter.ToString(pattern);
    return new Regex(patternString).Matches(targetString).Count;
}

今天的关于计算字节数组的SHA-1计算数组所占字节数的分享已经结束,谢谢您的关注,如果想了解更多关于16进制字符串和字节数组的互转、byte字节数组的压缩、c# – 从字节数组中读取行(不将字节数组转换为字符串)、c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数的相关知识,请在本站进行查询。

本文标签: