如何在 Java 中加密和解密数据

x33g5p2x  于2021-10-26 转载在 Java  
字(1.8k)|赞(0)|评价(0)|浏览(298)

在本教程中,我们将以简单的方式解释如何 EncryptDecrypt 纯文本数据。在这个例子中,我们将使用一个简单的 Key 来加密数据,并使用相同的 Key 来解密加密的数据。

3 用作加密和解密数据的密钥。

什么是加密?

Encryption 是一种对数据进行编码的机制,只有经过授权的成员才能访问它。编码数据称为 Cipher Text

什么是解密?

Decryption 是一种技术,其中我们使用加密数据时使用的相同 Key 解密加密数据。

注意: 在本例中,我们使用相同的 Key 来加密和解密数据。当加密和解密密钥相同时,这称为 Symmetric key / Private key

纯文本文件

WebSparrow.org is an Internet company. It will provide high quality and well tested technical pages for Internet techie.

加密示例

在此示例中,我们将从 PlainText.txt 文件中读取数据并应用加密密钥并将加密数据写入 CipherText.txt 文件中。
EncryptionExp.java

package org.websparrow;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class EncryptionExp {
	public static void main(String[] args) {
		try {

			int ctr;

			FileInputStream inputStream = new FileInputStream("PlainText.txt");
			FileOutputStream outputStream = new FileOutputStream("CipherText.txt");

			while ((ctr = inputStream.read()) != -1) {
				ctr -= 3; // 3 is the encryption key .
				System.out.print((char) ctr);
				outputStream.write(ctr);
			}
			outputStream.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

输出:

最后,纯文本已按如下所示进行编码……

Tb_Pm^oolt+lodfp^kFkqbokbq`ljm^kv+Fqtfiimolsfabefdenr^ifqv^katbiiqbpqbaqb`ekf`^im^dbpcloFkqbokbqqb`efb+

解密示例

本例将上面加密的数据解密,写入OriginalText.txt
DecryptionExp.java

package org.websparrow;

import java.io.FileInputStream;
import java.io.FileOutputStream;

class DecryptionExp {
	public static void main(String[] args) {
		try {

			int ctr;

			FileInputStream inputStream = new FileInputStream("CipherText.txt");
			FileOutputStream outputStream = new FileOutputStream("OriginalText.txt");

			while ((ctr = inputStream.read()) != -1) {

				ctr += 3; // 3 is the decryption key.

				System.out.print((char) ctr);
				outputStream.write(ctr);
				Thread.sleep(10);
			}
			outputStream.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

输出:

上面的编码文本已被解码,如下所示......

WebSparrow.org is an Internet company. It will provide high quality and well tested technical pages for Internet techie.

相关文章

微信公众号

最新文章

更多