天天看點

Java 位元組數組與String的互相轉換錯誤

  1. 遇到的問題:Byte[]數組轉化為String,String再轉化成Byte數組時,兩個位元組數組長度不一。
  2. 問題描述:今天我在學習Java實作的RSA加密算法的時候,将加密後的位元組數組用String來存儲(為了友善檢視以及傳輸),但是在解密的時候卻出錯了,代碼如下:
package com.yufeng.utils;

/**
 * Created by Feng on 2016/6/26.
 */

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

public class RSAUtil2 {
    public static final String PUBLIC = "public";
    public static final String PRIVATE = "private";
    public static Map<String,Object> generator(){
        Map<String,Object> result = new HashMap<String, Object>();
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            KeyPair pair = generator.generateKeyPair();
            result.put(PUBLIC, pair.getPublic());
            result.put(PRIVATE,pair.getPrivate());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String encrypt(String message, PublicKey publicKey, String enct){
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE,publicKey);
            byte[] trst= cipher.doFinal(message.getBytes());
            System.out.println(trst.length);
            return new String(trst,enct);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String decrypt(String message,PrivateKey key,String enct){
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE,key);
            System.out.println(message.getBytes().length);
            byte[] trst = cipher.doFinal(message.getBytes());
            return new String(trst,enct);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static void main(String[] args) {
        Map<String,Object> keyPair  = generator();
        String message = "test";
        String result = encrypt(message, (PublicKey) keyPair.get(PUBLIC), "UTF-8");
        System.out.println(result);
        System.out.println(decrypt(result, (PrivateKey) keyPair.get(PRIVATE),"UTF-8"));
    }
}
           

其中,我在加密和解密的函數中輸出了兩個位元組數組的長度,結果如下:

Java 位元組數組與String的互相轉換錯誤

3.問題分析:String底層是以Char數組記錄的,Byte會轉化成Char,因為Char和Byte的長度不同,是以在轉化的過程中會對Byte進行整合,主要是用0填充.

4.解決方案:将位元組轉化為兩位BCD碼

以下别人是封裝好的一個類:

package com.yufeng.utils;

import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Feng on 2016/6/26.
 */
public class RSAUtils {

    /**
     * 生成公鑰和私鑰
     * @throws NoSuchAlgorithmException
     */
    public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException {
        HashMap<String, Object> map = new HashMap<String, Object>();
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize();
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        map.put("public", publicKey);
        map.put("private", privateKey);
        return map;
    }

    /**
     * 使用模和指數生成RSA公鑰
     * 注意:【此代碼用了預設補位方式,為RSA/None/PKCS1Padding,不同JDK預設的補位方式可能不同,如Android預設是RSA
     * /None/NoPadding】
     *
     * @param modulus  模
     * @param exponent 指數
     * @return
     */
    public static RSAPublicKey getPublicKey(String modulus, String exponent) {
        try {
            BigInteger b1 = new BigInteger(modulus);
            BigInteger b2 = new BigInteger(exponent);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 使用模和指數生成RSA私鑰
     * 注意:【此代碼用了預設補位方式,為RSA/None/PKCS1Padding,不同JDK預設的補位方式可能不同,如Android預設是RSA
     * /None/NoPadding】
     *
     * @param modulus  模
     * @param exponent 指數
     * @return
     */
    public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
        try {
            BigInteger b1 = new BigInteger(modulus);
            BigInteger b2 = new BigInteger(exponent);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 公鑰加密
     *
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        // 模長
        int key_len = publicKey.getModulus().bitLength() / ;
        // 加密資料長度 <= 模長-11
        String[] datas = splitString(data, key_len - );
        String mi = "";
        //如果明文長度大于模長-11則要分組加密
        for (String s : datas) {
            mi += bcd2Str(cipher.doFinal(s.getBytes()));
        }
        return mi;
    }

    /**
     * 私鑰解密
     *
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        //模長
        int key_len = privateKey.getModulus().bitLength() / ;
        byte[] bytes = data.getBytes();
        byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
        System.err.println(bcd.length);
        //如果密文長度大于模長則要分組解密
        String ming = "";
        byte[][] arrays = splitArray(bcd, key_len);
        for (byte[] arr : arrays) {
            ming += new String(cipher.doFinal(arr));
        }
        return ming;
    }

    /**
     * ASCII碼轉BCD碼
     */
    public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
        byte[] bcd = new byte[asc_len / ];
        int j = ;
        for (int i = ; i < (asc_len + ) / ; i++) {
            bcd[i] = asc_to_bcd(ascii[j++]);
            bcd[i] = (byte) (((j >= asc_len) ?  : asc_to_bcd(ascii[j++])) + (bcd[i] << ));
        }
        return bcd;
    }

    public static byte asc_to_bcd(byte asc) {
        byte bcd;

        if ((asc >= '0') && (asc <= '9'))
            bcd = (byte) (asc - '0');
        else if ((asc >= 'A') && (asc <= 'F'))
            bcd = (byte) (asc - 'A' + );
        else if ((asc >= 'a') && (asc <= 'f'))
            bcd = (byte) (asc - 'a' + );
        else
            bcd = (byte) (asc - );
        return bcd;
    }

    /**
     * BCD轉字元串
     */
    public static String bcd2Str(byte[] bytes) {
        char temp[] = new char[bytes.length * ], val;

        for (int i = ; i < bytes.length; i++) {
            val = (char) (((bytes[i] & ) >> ) & );
            temp[i * ] = (char) (val >  ? val + 'A' -  : val + '0');

            val = (char) (bytes[i] & );
            temp[i *  + ] = (char) (val >  ? val + 'A' -  : val + '0');
        }
        return new String(temp);
    }

    /**
     * 拆分字元串
     */
    public static String[] splitString(String string, int len) {
        int x = string.length() / len;
        int y = string.length() % len;
        int z = ;
        if (y != ) {
            z = ;
        }
        String[] strings = new String[x + z];
        String str = "";
        for (int i = ; i < x + z; i++) {
            if (i == x + z -  && y != ) {
                str = string.substring(i * len, i * len + y);
            } else {
                str = string.substring(i * len, i * len + len);
            }
            strings[i] = str;
        }
        return strings;
    }

    /**
     * 拆分數組
     */
    public static byte[][] splitArray(byte[] data, int len) {
        int x = data.length / len;
        int y = data.length % len;
        int z = ;
        if (y != ) {
            z = ;
        }
        byte[][] arrays = new byte[x + z][];
        byte[] arr;
        for (int i = ; i < x + z; i++) {
            arr = new byte[len];
            if (i == x + z -  && y != ) {
                System.arraycopy(data, i * len, arr, , y);
            } else {
                System.arraycopy(data, i * len, arr, , len);
            }
            arrays[i] = arr;
        }
        return arrays;
    }

    public static void main(String[] args) throws Exception {
        HashMap<String,Object> keyPair  = getKeys();
        String message = "加密資訊";
        String result = encryptByPublicKey(message, (RSAPublicKey) keyPair.get("public"));
        System.out.println(result);
        System.out.println(decryptByPrivateKey(result, (RSAPrivateKey) keyPair.get("private")));
    }
}
           

參考:

http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html

http://yuncode.net/code/c_54c21d8781bae60