android把255转换成字节,Java Android - 已解密的字节数组长度为255字节,而不是“Hello World!”长度...

开发者在Android应用中尝试解密外部存储的许可密钥,遇到问题:明明10字符的字符串解密后却只有255字节,包含大量问号和黑色方块。探讨原因及解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我正在阅读很多内容,因为我的Android应用程序实现了加密/解密算法。我正在实施从我的网站下载并存储在我的Android设备的外部存储中的许可密钥。应用程序读取文件的内容并使用服务器公钥对其进行解密(是的,我知道我应该使用客户端私钥,但对我的目的来说没关系)。问题在于最终的字符串里面有许多带问号的黑色方块。我已经在stackoverflow上读过很多其他帖子,但我认为“唯一”的问题是,即使字符串中应该有10个字符,该字符串也是长255字节(具有2048位RSA密钥)和剩下的字符充满黑色“”。为什么newPlainText var不如“Hello World!” ?下面我的代码...非常感谢提前!Java Android - 已解密的字节数组长度为255字节,而不是“Hello World!”长度

public boolean licenseValid() throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{

java.io.File file = new java.io.File(Environment.getExternalStorageDirectory().toString() ,

"/folder/file.lic");

byte[] fileBArray = new byte[(int)file.length()];

FileInputStream fis = new FileInputStream(file);

// Read in the bytes

int offset = 0;

int numRead = 0;

while (offset < fileBArray.length

&& (numRead=fis.read(fileBArray, offset, fileBArray.length-offset)) >= 0) {

offset += numRead;

}

// Ensure all the bytes have been read in

if (offset < fileBArray.length) {

throw new IOException("Could not completely read file "+file.getName());

}

fis.close();

// Decrypt the ciphertext using the public key

PublicKey pubKey = readKeyFromFile();

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.DECRYPT_MODE, pubKey);

byte[] newPlainText = cipher.doFinal(fileBArray);

// THE FOLLOWING TOAST PRINTS MANY > AND THAN THE DECRYPTED MESSAGE. THE TOTAL NUMBER OF CHARACTERS IS 255, EVEN IF I CHANGE ENCRYPTED TEXT!

toast(String.valueOf(cipher.doFinal(fileBArray).length));

if (new String(newPlainText, "utf-8").compareTo("Hello World!") == 0)

return true;

else

return false;

}

PublicKey readKeyFromFile() throws IOException {

Resources myResources = getResources();

//public key filename "pub.lic"

InputStream is = myResources.openRawResource(R.raw.pub);

ObjectInputStream oin =

new ObjectInputStream(new BufferedInputStream(is));

try {

BigInteger m = (BigInteger) oin.readObject();

BigInteger e = (BigInteger) oin.readObject();

RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);

KeyFactory fact = KeyFactory.getInstance("RSA");

PublicKey pubKey = fact.generatePublic(keySpec);

return pubKey;

} catch (Exception e) {

throw new RuntimeException("Spurious serialisation error", e);

} finally {

oin.close();

}

}

2011-10-25

Vale

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值