使用java加密整数 [英] Using java to encrypt integers

查看:196
本文介绍了使用java加密整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用java.security和javax.crypto在java中加密一些整数。

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

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

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?

我应该将整数转换为字符串和字符串到byte []?这似乎太低效了。

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?

让我知道。

提前感谢。

jbu

推荐答案

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

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

然后稍后解密:

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

这篇关于使用java加密整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆