使用java对整数进行加密

发布于 2024-07-09 14:47:25 字数 262 浏览 5 评论 0原文

我正在尝试使用 java.security 和 javax.crypto 加密 java 中的一些整数。

问题似乎是 Cipher 类仅加密字节数组。 我无法直接将整数转换为字节字符串(或者可以吗?)。 做这个的最好方式是什么?

我应该将整数转换为字符串并将字符串转换为 byte[] 吗? 这看起来效率太低了。

有谁知道快速/简单或有效的方法吗?

请告诉我。

提前致谢。

吉布

I'm trying to encrypt some integers in java using java.security and javax.crypto.

The problem seems to be that the Cipher class only encrypts byte arrays. I can't directly convert an integer to a byte string (or can I?). What is the best way to do this?

Should I convert the integer to a string and the string to byte[]? This seems too inefficient.

Does anyone know a quick/easy or efficient way to do it?

Please let me know.

Thanks in advance.

jbu

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

秋凉 2024-07-16 14:47:25

您可以使用 DataOutputStream 将整数转换为 byte[],如下所示:

ByteArrayOutputStream baos = new ByteArrayOutputStream ();
DataOutputStream dos = new DataOutputStream (baos);
dos.writeInt (i);
byte[] data = baos.toByteArray();
// do encryption

然后稍后解密:

byte[] decrypted = decrypt (data);
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();

You can turn ints into a byte[] using a DataOutputStream, like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream ();
DataOutputStream dos = new DataOutputStream (baos);
dos.writeInt (i);
byte[] data = baos.toByteArray();
// do encryption

Then to decrypt it later:

byte[] decrypted = decrypt (data);
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();
皇甫轩 2024-07-16 14:47:25

您还可以使用 BigInteger 进行转换:

 BigInteger.valueOf(integer).toByteArray();

You can also use BigInteger for conversion:

 BigInteger.valueOf(integer).toByteArray();
紫瑟鸿黎 2024-07-16 14:47:25

就用蔚来吧。 它是为此特定目的而设计的。 ByteBuffer 和 IntBuffer 将快速、高效、优雅地满足您的需求。 它将处理大/小尾数转换、高性能 IO 的“直接”缓冲区,甚至可以将数据类型混合到字节缓冲区中。

将整数转换为字节:

ByteBuffer bbuffer = ByteBuffer.allocate(4*theIntArray.length);
IntBuffer ibuffer = bbuffer.asIntBuffer(); //wrapper--doesn't allocate more memory
ibuffer.put(theIntArray);                  //add your int's here; can use 
                                           //array if you want
byte[] rawBytes = bbuffer.array();         //returns array backed by bbuffer--
                                           //i.e. *doesn't* allocate more memory

将字节转换为整数:

ByteBuffer bbuffer = ByteBuffer.wrap(rawBytes);
IntBuffer ibuffer = bbuffer.asIntBuffer();
while(ibuffer.hasRemaining())
   System.out.println(ibuffer.get());      //also has bulk operators

Just use NIO. It's designed for this specific purpose. ByteBuffer and IntBuffer will do what you need quickly, efficiently, and elegantly. It'll handle big/little endian conversion, "direct" buffers for high performance IO, and you can even mix data types into the byte buffer.

Convert integers into bytes:

ByteBuffer bbuffer = ByteBuffer.allocate(4*theIntArray.length);
IntBuffer ibuffer = bbuffer.asIntBuffer(); //wrapper--doesn't allocate more memory
ibuffer.put(theIntArray);                  //add your int's here; can use 
                                           //array if you want
byte[] rawBytes = bbuffer.array();         //returns array backed by bbuffer--
                                           //i.e. *doesn't* allocate more memory

Convert bytes into integers:

ByteBuffer bbuffer = ByteBuffer.wrap(rawBytes);
IntBuffer ibuffer = bbuffer.asIntBuffer();
while(ibuffer.hasRemaining())
   System.out.println(ibuffer.get());      //also has bulk operators
就此别过 2024-07-16 14:47:25

我发现下面的代码可能对你有帮助,因为 Java 中的 Integer 总是 4 个字节长。

public static byte[] intToFourBytes(int i, boolean bigEndian) {  
    if (bigEndian) {  
        byte[] data = new byte[4];  
        data[3] = (byte) (i & 0xFF);  
        data[2] = (byte) ((i >> 8) & 0xFF);  
        data[1] = (byte) ((i >> 16) & 0xFF);  
        data[0] = (byte) ((i >> 24) & 0xFF);  
        return data;  

    } else {  
        byte[] data = new byte[4];  
        data[0] = (byte) (i & 0xFF);  
        data[1] = (byte) ((i >> 8) & 0xFF);  
        data[2] = (byte) ((i >> 16) & 0xFF);  
        data[3] = (byte) ((i >> 24) & 0xFF);  
        return data;  
    }  
}  

您可以在此处找到有关 bigEndian 参数的更多信息:
http://en.wikipedia.org/wiki/Endianness

I have found the following code that may help you, since Integer in Java is always 4 bytes long.

public static byte[] intToFourBytes(int i, boolean bigEndian) {  
    if (bigEndian) {  
        byte[] data = new byte[4];  
        data[3] = (byte) (i & 0xFF);  
        data[2] = (byte) ((i >> 8) & 0xFF);  
        data[1] = (byte) ((i >> 16) & 0xFF);  
        data[0] = (byte) ((i >> 24) & 0xFF);  
        return data;  

    } else {  
        byte[] data = new byte[4];  
        data[0] = (byte) (i & 0xFF);  
        data[1] = (byte) ((i >> 8) & 0xFF);  
        data[2] = (byte) ((i >> 16) & 0xFF);  
        data[3] = (byte) ((i >> 24) & 0xFF);  
        return data;  
    }  
}  

You can find more information about the bigEndian parameter here:
http://en.wikipedia.org/wiki/Endianness

那小子欠揍 2024-07-16 14:47:25

创建一个 4 字节数组,并通过按位 AND 和位移位分 4 步将 int 复制到该数组,就像 Paulo 所说的那样。

但请记住,AES 和 DES 等块算法适用于 8 或 16 字节块,因此您需要将数组填充到算法所需的值。 也许将 8 字节数组的前 4 个字节保留为 0,其他 4 个字节包含整数。

create a 4-byte array and copy the int to the array in 4 steps, with bitwise ANDs and bitshifting, like Paulo said.

But remember that block algorithms such as AES and DES work with 8 or 16 byte blocks so you will need to pad the array to what the algorithm needs. Maybe leave the first 4 bytes of an 8-byte array as 0's, and the other 4 bytes contain the integer.

一城柳絮吹成雪 2024-07-16 14:47:25

只需使用:

    Integer.toString(int).getBytes();

确保使用原始 int 并且 getBytes() 将返回一个字节数组。 不需要做任何其他复杂的事情。

要转换回来:

    Integer.parseInt(encryptedString);

Just use:

    Integer.toString(int).getBytes();

Make sure you use your original int and getBytes() will return a byte array. No need to do anything else complicated.

To convert back:

    Integer.parseInt(encryptedString);
笔落惊风雨 2024-07-16 14:47:25

我的简单解决方案是通过将整数的 ASCII 值按您提供的密钥进行移位,将整数加密为字符串。

解决方案如下:

public String encodeDiscussionId(int Id) {

    String tempEn = Id + "";
    String encryptNum ="";
    for(int i=0;i<tempEn.length();i++) {
        int a = (int)tempEn.charAt(i);
        a+=148113;
        encryptNum +=(char)a;
    }
    return encryptNum;
}

public Integer decodeDiscussionId(String encryptText) {

    String decodeText = "";
    for(int i=0;i<encryptText.length();i++) {
        int a= (int)encryptText.charAt(i);
        a -= 148113;
        decodeText +=(char)a;
    }
    int decodeId = Integer.parseInt(decodeText);
    return decodeId;
}

编码步骤:

  1. 这里,首先通过以下方式将给定的整数转换为字符串: String temp = GiveInt + ""
  2. 扫描字符串的每个字符,读取该字符的 ASCII 并将其添加为在本例中,密钥为 148113。
  3. 将移位的Integer 转换为Character 并连接到String encryptNum 最后返回它。

解码步骤:

  1. 扫描字符串的每个字符,读取该字符的 ASCII,然后用密钥将其减去,如前所述。
  2. 将该值转换为字符并与 decodeText 连接。

由于之前的编码输出始终为 String '???',并根据输入 Id 的位数而变化。

My Simple Solution is that Encrypt Integer to the String by shifting ASCII Value of the Integer by the secret key you Provide.

Here is the Solution:

public String encodeDiscussionId(int Id) {

    String tempEn = Id + "";
    String encryptNum ="";
    for(int i=0;i<tempEn.length();i++) {
        int a = (int)tempEn.charAt(i);
        a+=148113;
        encryptNum +=(char)a;
    }
    return encryptNum;
}

public Integer decodeDiscussionId(String encryptText) {

    String decodeText = "";
    for(int i=0;i<encryptText.length();i++) {
        int a= (int)encryptText.charAt(i);
        a -= 148113;
        decodeText +=(char)a;
    }
    int decodeId = Integer.parseInt(decodeText);
    return decodeId;
}

Steps to Encode:

  1. Here, First you convert the Given Integer into String by: String temp = givenInt + ""
  2. Scan each character of String, Read ASCII of that character and add it with secret key as 148113 in this case.
  3. Convert shifted Integer into Character and concatenate to the String encryptNum and finally return it.

Steps to Decode:

  1. Scan each character of String, Read ASCII of that character and subtract it with secret key as previous.
  2. Convert that value to character and concatenate with decodeText.

As previous encode output is always String '???' and vary according to number of digits of input Id.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文