【发布时间】:2016-10-19 11:35:04
【问题描述】:
我正在通过 java 中本地 repo 的证书加密解密文件。 但对于包含表格、图表的文字处理文件,文件与实际文件并不相同。我正在使用普通文件输入/输出流。 任何帮助都会很有用,谢谢。
public int encryptFileWithpubkey(String filepath,PublicKey pubkey){
int retval=0;
FileInputStream fis = null;
File file=null;
final String location = filepath;
PublicKey pubKey= pubkey;
try{
try {
fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(location);
}
});
} catch (PrivilegedActionException e) {
throw (FileNotFoundException) e.getException();
}
InputStream is = fis;
//long length = file.length();
byte[] bytes = new byte[fis.available()];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
is.close();
file=null;
String encString="";
int iFixedLen=110;
if(bytes.length>=iFixedLen){
int noOfBlocks=(int)Math.ceil((bytes.length/110.0));
// System.out.println("Noof blocks :"+noOfBlocks);
for(int i=0;i<noOfBlocks;i++){
byte[] tempStr=null;
if(i==noOfBlocks-1){
//System.out.println("Last block");
tempStr=new byte[(bytes.length-(i*iFixedLen))];
System.arraycopy(bytes, (i*iFixedLen), tempStr, 0,(bytes.length-(i*iFixedLen)));
}
else
{
//System.out.println("i : "+i);
tempStr=new byte[iFixedLen];
//tempStr=new byte[iFixedLen];
System.arraycopy(bytes, (i*iFixedLen), tempStr, 0,iFixedLen);
//tempStr=plainText.substring(0,110) ;
//plainText=plainText.substring(110);
}
encString+= encryptBytes(tempStr,pubKey)+" ";
}
encString=encString.substring(0,encString.length()-1);
retval=noOfBlocks;
}else{
encString=encryptBytes(bytes,pubKey);
retval=1;
}
FileOutputStream fos = null;
try {
fos = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileOutputStream>() {
public FileOutputStream run() throws FileNotFoundException {
return new FileOutputStream(location);
}
});
} catch (PrivilegedActionException e) {
throw (FileNotFoundException) e.getException();
}
fos.write(encString.getBytes());
fos.close();
}catch(Exception e){
e.printStackTrace();
return 0;
}
return retval;
}
encryptBytes 函数如下:
public String encryptBytes(byte[] rawData,PublicKey pubkey){
String retval=null;
try{
byte[] rawByteData=rawData;
Cipher cp=Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cp.init( Cipher.ENCRYPT_MODE,pubkey);
byte[] getDat=cp.doFinal(rawByteData);
retval=java.util.Base64.getEncoder().encodeToString(getDat);
}catch(Exception e)
{
e.printStackTrace();
}
return retval;
}
【问题讨论】:
-
您的代码中某处存在错误。没看到也能这么说。
-
@Henry 简单的文本内容没有问题,但如果是图表和表格,则无法正常工作。
-
所以在加密图表和表格时,您的代码中存在错误。可能会得到什么样的答案?
-
那么如何编码解码包含这些内容的文本文件?
-
@R.chow 以正确的方式进行操作。
标签: java x509certificate public-key-encryption