簡體   English   中英

Java CipherInputStream將奇怪的字符放在行首

[英]Java CipherInputStream puts strange character at beginning of line

我正在測試Java中的文本加密。 問題是我在行首出現一些奇怪的字符,但我不明白為什么。 當我刪除加密時,一切都會順利進行。

復制到Notepad ++后,輸出如下所示:

Hello

<SOH>dear

<STX><STX>world

為什么會出現奇怪的控制字符?

碼:

public class Test {
        private static File file;
        private static final byte[] STAT_KEY = { -1, -2, 3, 4, -5, -6, -7, 8 };
        static {
            file = new File("MyFile.txt");
        }

        private static Cipher getCipher(int mode) throws InvalidKeyException, NoSuchAlgorithmException,
                InvalidKeySpecException, NoSuchPaddingException {
            DESKeySpec dks = new DESKeySpec(STAT_KEY);
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey desKey = skf.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(mode, desKey);
            return cipher;
        }

        private static void appendToFile(String item) throws Exception {
            CipherOutputStream cos = null;
            try {
                cos = new CipherOutputStream(new FileOutputStream(file, true), getCipher(Cipher.ENCRYPT_MODE));
                cos.write((item + String.format("%n")).getBytes());
            } finally {
                cos.close();
            }
        }

        private static void readFromFile() throws Exception {
            CipherInputStream cis = null;
            try {
                cis = new CipherInputStream(new FileInputStream(file), getCipher(Cipher.DECRYPT_MODE));
                int content;
                while ((content = cis.read()) != -1) {
                    System.out.print((char) content);
                }
            } finally {
                cis.close();
            }
        }

        public static void main(String[] args) throws Exception {
            String[] items = { "Hello", "dear", "world" };
            for (String item : items) {
                appendToFile(item);
            }
            readFromFile();
        }
    }

PD:對不起,我處理異常的方式:)

類似於ObjectOutputStreamCipherOutputStream的編寫方式不允許直接附加。

append(data1)+ append(data2)+ append(data3)!= append(數據1+數據2+數據3)

您需要添加自己的定界不同數據塊的方法。 有趣? 字符是CipherOutputStream使用的私有控制字符。

如果您只是正常地加密數據(即使用Cipher對象)並將輸出寫入由合適的定界符包圍的文件中,則生活可能會更輕松。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM