【发布时间】:2015-06-23 08:56:52
【问题描述】:
所以我有一个 AES 算法来加密我的字节数组,所以 -128 到 127。 问题是(长话短说)我不希望 AES 在加密后将我的任何字节转换为 -1 或 127(因为如果我转换为 16 位,由于某种原因它们都是 0),然后我无法正确解密.有什么办法吗?
我的应用程序运行如下:
声卡(16bit) -> 字节数组(8bit) -> AES.encr -> 加密字节数组(8bit) -> 套接字(8bit 传输) -> 加密字节数组(16bit) -> 数组加密字节(8bit) -> AES.decr -> 解密字节数组(8bit)
public static int linear2ulaw(int pcm_val){ // 2's complement (16-bit range)
int mask;
int seg;
//unsigned char uval;
int uval;
// Get the sign and the magnitude of the value.
if (pcm_val<0){
pcm_val=BIAS-pcm_val;
mask=0x7F;
}
else{
pcm_val+=BIAS;
mask=0xFF;
}
// Convert the scaled magnitude to segment number.
seg=search(pcm_val,seg_end);
// Combine the sign, segment, quantization bits; and complement the code word.
if (seg>=8) return (0x7F^mask); // out of range, return maximum value.
else{
uval=(seg<<4) | ((pcm_val>>(seg+3)) & 0xF);
return (uval^mask);
}
}
static int search(int val, int[] table){
for (int i=0; i<table.length; i++)
if (val<=table[i]) return i;
return table.length;
}
static final int SIGN_BIT=0x80; // Sign bit for a A-law byte.
static final int QUANT_MASK=0xf; // Quantization field mask.
static final int NSEGS=8; // Number of A-law segments.
static final int SEG_SHIFT=4; // Left shift for segment number.
static final int SEG_MASK=0x70; // Segment field mask.
public static final int BIAS=0x84;
static final int[] seg_end={ 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF };
public static int ulaw2linear(int u_val){
int t;
// Complement to obtain normal u-law value.
u_val=~u_val;
// Extract and bias the quantization bits. Then shift up by the segment number and subtract out the bias.
t=((u_val&QUANT_MASK)<<3) + BIAS;
//t<<=((unsigned)u_val&SEG_MASK)>>SEG_SHIFT;
t<<=(u_val&SEG_MASK)>>SEG_SHIFT;
return ((u_val&SIGN_BIT)!=0)? (BIAS-t) : (t-BIAS);
}
【问题讨论】:
-
请发布将代码从 8 位转换为 16 位的代码。底线:您没有尝试以正确的方式解决问题;如果你真的需要[像base64编码一样编码]、发送、取消编码然后解密,那么获取你的数据、对其进行加密、对其进行编码会更有意义
-
我并不是说您可能对编码和加密的顺序不正确,但问题在于转换。因为无论哪种方式,在加密时都会出现 -1 和/或 127,并且 127 将始终转换为 -1,这对解密不利。 (我编辑了第一篇并放了代码)
-
首先,请注意(使用 2 的补码)-1 是 0x11111111,127 是 0x01111111(即它们的 7 个低位都设置为 1,唯一的区别是高/符号位)。此外,当我调用 linear_2ulaw(-1) 和 linear_2ualaw(127) 时,两者都不返回 0... 一个返回 127,一个返回 239。您是在 DSP 上运行它还是在 int 为 16 位的东西上运行它? [对 int 进行查找/替换缩写,我得到 127 / 215(以及 prshortf 不是有效函数的错误)或者这不是丢失信息的函数?
-
好吧,在我触摸它之前信息就丢失了,因为我通过套接字发送 8 位(出于速度原因,16 位是滞后的),我必须执行 ais = AudioSystem.getAudioInputStream(lineFormat, ais) at接收者,意思是 ais.read(buffer,0,buffer.length) 将返回 16 位的缓冲区,-1 和 127 的转换问题是 0x0 和 0x0。所以我发送 8 位缓冲区示例: buffer[1]= -1, buffer[2]=100, buffer[3]=127 我收到 buffer[1]=0, buffer[2]=0, buffer[3]= (-52),缓冲区[4]=(-2),缓冲区[5]=0,缓冲区[6]=0。原因是如果前两个 0,0 代表 -1 或 127,我无法做出任何改变。
-
但不是 ais = AudioSystem.getAudioInputStream(lineFormat, ais) 是问题所在,因为我发布了 linear=ulaw2linear(-1) 和 linear=ulaw2linear(127) 的“外部转换”使得linear=0,它是一个 int,没有 DSP。
标签: java sockets encryption byte aes