在本教程中,我们将以简单的方式解释如何 Encrypt
和 Decrypt
纯文本数据。在这个例子中,我们将使用一个简单的 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.
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/java/how-to-encrypt-and-decrypt-data-in-java
内容来源于网络,如有侵权,请联系作者删除!