您当前的位置:首页 > 互联网教程

Java使用base64时字符串中间包含null被编译成“”

发布时间:2025-05-21 07:02:22    发布人:远客网络

Java使用base64时字符串中间包含null被编译成“”

一、Java使用base64时字符串中间包含null被编译成“”

在使用Java的Base64编码和解码时,如果字符串中包含null值,则可能会导致字符串中的null值被编译为空字符串(“”)。这是因为Base64编码通常是基于字节数组的,而字符串在Java中是Unicode编码,因此在编码和解码过程中,字符串可能会被解释为null字符。

为了避免这种情况,您可以将字符串转换为字节数组,然后再进行Base64编码和解码。您可以使用Java的getBytes()方法将字符串转换为字节数组,并使用new String()方法将字节数组转换回字符串。

以下是一个简单的例子,展示了如何在Java中使用Base64编码和解码字符串:

public static void main(String[] args){

String originalString="Hello, World!\0";

byte[] originalBytes= originalString.getBytes();

// Encode the original string as a base64 string

String encodedString= Base64.getEncoder().encodeToString(originalBytes);

System.out.println("Encoded String:"+ encodedString);

// Decode the base64 string back to the original string

byte[] decodedBytes= Base64.getDecoder().decode(encodedString);

String decodedString= new String(decodedBytes);

System.out.println("Decoded String:"+ decodedString);

Encoded String: SGVsbG8sIFdvcmxkITAK

Decoded String: Hello, World!\0

这样,您就可以保证字符串中的null值不会在Base64编码和解码过

程中被丢失,并可以保证编码和解码的字符串与原始字符串完全匹配。

二、JAVA怎么将PDF的base64转换成jpg的base64

import org.apache.pdfbox.pdmodel.PDDocument;

import org.apache.pdfbox.rendering.ImageType;

import org.apache.pdfbox.rendering.PDFRenderer;

import org.slf4j.LoggerFactory;

import com.aiait.base.service.impl.base.SearchServiceImpl;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.text.DecimalFormat;

import org.apache.commons.lang3.StringUtils;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

private static final Logger lOGGER= LoggerFactory.getLogger(PDFUtil.class);

public static void main(String[] args){

// pdfTojpg("C://Test//eClaimPDF//1//Others.pdf","C://Test//eClaimPDF//WrittenConfirmation.jpg");

lOGGER.info("base64PdfToJpg use time:"+ getDiffTime(timeDiffL, timeDiffE)+"s");

private static String base64PdfToJpg(String base64Pdf){

BASE64Decoder decoder= new BASE64Decoder();

pdf_bytes= decoder.decodeBuffer(base64Pdf);

try(final PDDocument document= PDDocument.load(pdf_bytes)){

int size= document.getNumberOfPages();

BufferedImage imageResult= null;

PDDocument pdDocument= document;

PDFRenderer renderer= new PDFRenderer(pdDocument);

/*根据总页数,按照50页生成一张长图片的逻辑,进行拆分*/

int pageLength= size;//有多少转多少

int totalCount= pdDocument.getNumberOfPages()/ pageLength+ 1;

for(int m= 0; m< totalCount; m++){

for(int i= 0; i< pageLength; i++){

int pageIndex= i+(m* pageLength);

if(pageIndex== pdDocument.getNumberOfPages()){

// 96为图片的dpi,dpi越大,则图片越清晰,图片越大,转换耗费的时间也越多

BufferedImage image= renderer.renderImageWithDPI(pageIndex, 106, ImageType.RGB);

int imageHeight= image.getHeight();

int imageWidth= image.getWidth();

//加个判断:如果m次循环后所剩的图片总数小于pageLength,则图片高度按剩余的张数绘制,否则会出现长图片下面全是黑色的情况

if((pdDocument.getNumberOfPages()- m* pageLength)< pageLength){

imageResult= new BufferedImage(width, imageHeight*(pdDocument.getNumberOfPages()- m* pageLength), BufferedImage.TYPE_INT_RGB);

imageResult= new BufferedImage(width, imageHeight* pageLength, BufferedImage.TYPE_INT_RGB);

singleImgRGB= image.getRGB(0, 0, width, imageHeight, null, 0, width);

imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width);

// System.out.println("m="+ m);

File outFile= new File("C://Test//eClaimPDF//WrittenConfirmation.png");

System.out.println(outFile.getName());

ImageIO.write(imageResult,"png", outFile);

ByteArrayOutputStream baos= new ByteArrayOutputStream();//io流

ImageIO.write(imageResult,"png", baos);//写入流中

byte[] jpg_Bytes= baos.toByteArray();//转换成字节

BASE64Encoder encoder= new BASE64Encoder();

jpg_base64= encoder.encodeBuffer(jpg_Bytes).trim();//转换成base64串

jpg_base64= jpg_base64.replaceAll("\n","").replaceAll("\r","");//删除 \r\n

// System.out.println("值为:"+"data:image/jpg;base64,"+jpg_base64);

return"data:image/jpg;base64,"+jpg_base64;

// private static String base64PdfToJpg(String base64Pdf){

// BASE64Decoder decoder= new BASE64Decoder();

// pdf_bytes= decoder.decodeBuffer(base64Pdf);

// try(final PDDocument document= PDDocument.load(pdf_bytes)){

// int size= document.getNumberOfPages();

// for(int i= 0; i< size; i++){

// BufferedImage image= new PDFRenderer(document).renderImageWithDPI(i, pdfdpi, ImageType.RGB);

// BufferedImage image= new PDFRenderer(document).

// ByteArrayOutputStream baos= new ByteArrayOutputStream();//io流

// ImageIO.write(image,"jpg", baos);//写入流中

// byte[] jpg_Bytes= baos.toByteArray();//转换成字节

// BASE64Encoder encoder= new BASE64Encoder();

// jpg_base64= encoder.encodeBuffer(jpg_Bytes).trim();//转换成base64串

// jpg_base64= jpg_base64.replaceAll("\n","").replaceAll("\r","");//删除 \r\n

// System.out.println("值为:"+"data:image/jpg;base64,"+jpg_base64);

// return"data:image/jpg;base64,"+jpg_base64;

private static void pdfTojpg(String pdfFilePath, String jpgFilePath){

File pdfFile= new File(pdfFilePath);

int idx= jpgFilePath.lastIndexOf('.');

String jpgprefix= StringUtils.substring(jpgFilePath, 0, idx);

BASE64Decoder decoder= new BASE64Decoder();

bytes= decoder.decodeBuffer(pdfBase64);

// try(final PDDocument document= PDDocument.load(pdfFile,"")){

try(final PDDocument document= PDDocument.load(bytes)){

int size= document.getNumberOfPages();

for(int i= 0; i< size; i++){

BufferedImage image= new PDFRenderer(document).renderImageWithDPI(i, pdfdpi, ImageType.RGB);

* ByteArrayOutputStream baos= new ByteArrayOutputStream();//io流

* ImageIO.write(image,"jpg", baos);//写入流中 byte[] imgBytes=

* baos.toByteArray();//转换成字节 BASE64Encoder encoder= new BASE64Encoder();

* String png_base64= encoder.encodeBuffer(imgBytes).trim();//转换成base64串

* png_base64= png_base64.replaceAll("\n","").replaceAll("\r","");//删除 \r\n

* System.out.println("值为:"+"data:image/jpg;base64,"+png_base64);

File jpgFile= new File(jpgprefix+"_"+ i+".jpg");

ImageIO.write(image,"jpg", jpgFile);

private static Double getDiffTime(Date lateTime, Date earlyTime){

DecimalFormat df=new DecimalFormat("0.00");//设置保留位数

return Double.valueOf(df.format((double)(lateTime.getTime()- earlyTime.getTime())/ 1000));

public static String pdfBase64="***"//from web网页链接, upload a PDF to get the base64 string(Base64- Online Base64 decoder and encoder)

三、java 给定十六位密钥 如何进行des加密

packagecom.palic.pss.afcs.worldthrough.common.util;

importjavax.crypto.spec.SecretKeySpec;

importrepack.com.thoughtworks.xstream.core.util.Base64Encoder;

publicstaticfinalStringcKey="assistant7654321";

*加密--把加密后的byte数组先进行二进制转16进制在进行base64编码

publicstaticStringencrypt(StringsSrc,StringsKey)throwsException{

thrownewIllegalArgumentException("ArgumentsKeyisnull.");

thrownewIllegalArgumentException(

"ArgumentsKey'lengthisnot16.");

byte[]raw=sKey.getBytes("ASCII");

SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE,skeySpec);

byte[]encrypted=cipher.doFinal(sSrc.getBytes("UTF-8"));

StringtempStr=parseByte2HexStr(encrypted);

Base64Encoderencoder=newBase64Encoder();

returnencoder.encode(tempStr.getBytes("UTF-8"));

*解密--先进行base64解码,在进行16进制转为2进制然后再解码

publicstaticStringdecrypt(StringsSrc,StringsKey)throwsException{

thrownewIllegalArgumentException("499");

thrownewIllegalArgumentException("498");

byte[]raw=sKey.getBytes("ASCII");

SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");

cipher.init(Cipher.DECRYPT_MODE,skeySpec);

Base64Encoderencoder=newBase64Encoder();

byte[]encrypted1=encoder.decode(sSrc);

StringtempStr=newString(encrypted1,"utf-8");

encrypted1=parseHexStr2Byte(tempStr);

byte[]original=cipher.doFinal(encrypted1);

StringoriginalString=newString(original,"utf-8");

publicstaticStringparseByte2HexStr(bytebuf[]){

StringBuffersb=newStringBuffer();

for(inti=0;i<buf.length;i++){

Stringhex=Integer.toHexString(buf[i]&0xFF);

sb.append(hex.toUpperCase());

publicstaticbyte[]parseHexStr2Byte(StringhexStr){

byte[]result=newbyte[hexStr.length()/2];

for(inti=0;i<hexStr.length()/2;i++){

inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);

intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),

result[i]=(byte)(high*16+low);

publicstaticvoidmain(String[]args)throwsException{

*加密用的Key可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定

StringcKey="assistant7654321";

longlStart=System.currentTimeMillis();

StringenString=encrypt(cSrc,cKey);

System.out.println("加密后的字串是:"+enString);

longlUseTime=System.currentTimeMillis()-lStart;

System.out.println("加密耗时:"+lUseTime+"毫秒");

lStart=System.currentTimeMillis();

StringDeString=decrypt(enString,cKey);

System.out.println("解密后的字串是:"+DeString);

lUseTime=System.currentTimeMillis()-lStart;

System.out.println("解密耗时:"+lUseTime+"毫秒");