所以我有一个AES算法来加密我的字节数组,所以-128到127。问题是(长篇大论)我不希望AES在加密后将我的任何字节转换为-1或127 (因为如果我转换为16位,出于某种原因,这两个字节都是0),并且我无法正确解密。有没有办法做到这一点?
我的应用程序运行如下所示:
声卡(16位) ->字节数组(8位) -> AES.encr ->加密字节数组(8位) ->套接字(8位传输) ->加密字节数组(16位) ->加密字节数组(8位) -> AES.decr ->解密字节数组(8位)
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);
}发布于 2015-06-21 20:58:38
AES加密旨在产生随机外观的输出,因此,您不喜欢的字节将始终出现在字节输出中,平均每个字节大约每256个字节。您不能更改这一点,否则您将不会使用AES。
您可以做的是转换AES输出,这样不需要的字节就不会造成任何问题。通常的方法是使用Base64,正如@Foon建议的那样:
AES bytes -> to Base64 -> transmit -> from Base64 -> AES bytes.您可以将Base64视为绝对不包含-1或128的字节流。所有的Base64都在可打印的ASCII码范围内。您只需要记住在解密之前从Base64中检索原始字节。
如果Base64不是一种解决方案,那么还有其他可能性,但它们要复杂得多,您必须手动编程。使用Base64,您可以只导入库方法。
发布于 2015-06-21 04:18:08
看起来我知道该怎么做了。-1和127从来都不是问题,因为加密从来不会按顺序输出两个0,尽管可能会发生这种情况也很少见。问题出在ulaw编码上(但我不知道为什么)。我切换到了alaw,现在它工作得很好。我有一个小的背景噪音(加密和不加密),但它是可以接受的。
https://stackoverflow.com/questions/30957874
复制相似问题