📜  在Java应用程序中保护敏感数据的标准实践

📅  最后修改于: 2022-05-13 01:54:35.214000             🧑  作者: Mango

在Java应用程序中保护敏感数据的标准实践

我们可以使用加密技术来保存我们的数据。加密是将信息转换为隐藏信息真实含义的密码的方法。加密和解密信息的科学称为密码学。在计算中,未加密的数据也称为明文,加密的数据称为密文。用于对消息进行编码和解码的公式称为加密算法或密码。

让我们简要介绍一下要点,以更好地了解保护Java应用程序中敏感数据的标准实践。

  • 加密是一种加扰数据的方式,以便只有授权方才能理解信息。从技术上讲,它是将人类可读的明文转换为难以理解的文本的过程,称为密文。
  • 解密是将编码或加密的文本或其他数据转换回文本,以便您和计算机可以理解。
  • 密码,任何转换消息以隐藏其含义的方法。该术语还与密文或密文同义使用,指的是消息的加密形式。
  • Secured Random 类提供了一个加密强的随机数生成器。加密强随机数最低限度地符合 FIPS 140-2,加密模块的安全要求中指定的统计随机数生成器测试。

现在让我们来看看 SecureRandom 类的重要方法

1. generateSeed() 方法返回给定数量的种子,使用种子代计算。



句法:

generateSeed()

返回类型:字节数组(返回给定数量的种子,使用种子代计算)。

2 . setSeed() 方法为随机对象播种

返回类型:无效

例子:

Java
// Java Program Demonstrating How Can We Get Secured
// Random Numbers from SecureRandom class
 
// Importing required classes
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Try block to check for exceptions
        try {
 
            // Initialize a secure random number generator
            SecureRandom secureRandom
                = SecureRandom.getInstance("SHA1PRNG");
 
            // Method 1
            // Calling nextBytes method to generate Random
            // Bytes
            byte[] bytes = new byte[512];
            secureRandom.nextBytes(bytes);
 
            // Printing the SecureRandom number by
            // calling secureRandom.nextDouble()
            System.out.println(
                " Secure Random # generated by calling nextBytes() is "
                + secureRandom.nextDouble());
 
            // Method 2
            // Using setSeed(byte[]) to reseed a Random
            // object
            int seedByteCount = 10;
            byte[] seed
                = secureRandom.generateSeed(seedByteCount);
 
            secureRandom.setSeed(seed);
 
            System.out.println(
                " Secure Random # generated using setSeed(byte[]) is  "
                + secureRandom.nextDouble());
        }
 
        // Catch block to handle the exceptions
        catch (NoSuchAlgorithmException noSuchAlgo) {
            // Display message if it occurs
            System.out.println(" No Such Algorithm exists "
                               + noSuchAlgo);
        }
    }
}


Java
// Java Program to Illustrate AES Encryption
 
// Importing required classes
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
 
// Main class
class GFG {
 
    // Encryption function
    // function 1
    public static void encryptEcb(String filenamePlain,
                                  String filenameEnc,
                                  byte[] key)
        throws IOException, NoSuchAlgorithmException,
               NoSuchPaddingException, InvalidKeyException,
               IllegalBlockSizeException,
               BadPaddingException
    {
 
        // Creating cipher instance OF AES encryption
        Cipher cipher
            = Cipher.getInstance("AES/ECB/PKCS5PADDING");
 
        // Specifying the algorithm
        SecretKeySpec secretKeySpec
            = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
 
        // Try block to check for exceptions
        try (FileInputStream fis
             = new FileInputStream(filenamePlain);
 
             // Creating objects of BufferedInputStream,
             // FileOutputStream and BufferedOutputStream
             BufferedInputStream inputstream
             = new BufferedInputStream(fis);
             FileOutputStream outputstream
             = new FileOutputStream(filenameEnc);
             BufferedOutputStream bufferedOutputStream
             = new BufferedOutputStream(outputstream)) {
 
            // Defining the buffer
            byte[] ibufffer = new byte[1024];
 
            int length;
 
            // Reading while read buffer has data
            while ((length = inputstream.read(ibufffer))
                   != -1) {
 
                // Creating cipher with buffer
                byte[] obuffer
                    = cipher.update(ibufffer, 0, length);
 
                if (obuffer != null)
 
                    // Writing encrypted text to buffer
                    bufferedOutputStream.write(obuffer);
            }
 
            byte[] obuffer = cipher.doFinal();
 
            if (obuffer != null)
                bufferedOutputStream.write(obuffer);
        }
    }
 
    // Method 3
    // Decryption method
    public static void decryptEcb(String filenameEnc,
                                  String filenameDec,
                                  byte[] key)
        throws IOException, NoSuchAlgorithmException,
               NoSuchPaddingException, InvalidKeyException,
               IllegalBlockSizeException,
               BadPaddingException
    {
 
        // Try block to check for exceptions
        try (FileInputStream inputStream
             = new FileInputStream(filenameEnc);
             FileOutputStream outputStream
             = new FileOutputStream(filenameDec)) {
            // Defining buffer
            byte[] ibuffer = new byte[1024];
            int length;
 
            // Creating cipher instance OF AES decryption
            Cipher cipher = Cipher.getInstance(
                "AES/ECB/PKCS5PADDING");
            SecretKeySpec secretKeySpec
                = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
 
            // While input stream not empty
            while ((length = inputStream.read(ibuffer))
                   != -1) {
 
                // Reading into the buffer
                byte[] obuffer
                    = cipher.update(ibuffer, 0, length);
                if (obuffer != null)
 
                    // Now writing to output buffer
                    outputStream.write(obuffer);
            }
 
            byte[] obuffer = cipher.doFinal();
            if (obuffer != null)
                outputStream.write(obuffer);
        }
    }
 
    // Method 3
    // Main driver method
    public static void main(String[] args)
        throws IOException, NoSuchPaddingException,
               NoSuchAlgorithmException, BadPaddingException
               ,
               IllegalBlockSizeException,
               InvalidKeyException
    {
 
        // Display message
        System.out.println("/****AES Encryption*******/");
 
        // Placing the PDF path
        String pFileName
            = "/home/aniket/IdeaProjects/Gfg Programs/MAD FINAL.pdf";
        String cFileName = "your pdf.enc";
 
        // Placing the PDF name
        String decFileName = "your pdf.pdf";
 
        // Creating cipher key 56 bit key length
        byte[] cipher_key
            = "12345678901234561234567890123456".getBytes(
                "UTF-8");
        encryptEcb(pFileName, cFileName, cipher_key);
        decryptEcb(cFileName, decFileName, cipher_key);
 
        // Print and display the file credentials
        System.out.println(
            "file of encryption: " + pFileName + "\n"
            + "created encrypted file  : " + cFileName
            + "\n"
            + "created decrypted file  : " + decFileName);
    }
}


输出:

Secure Random # generated by calling nextBytes() is 0.8849167225465367
Secure Random # generated using setSeed(byte[]) is  0.7542495384908446

AES 加密

AES-128 使用 128 位密钥长度来加密和解密消息块,而 AES -192 使用 192 位密钥长度和 AES-256 使用 256 位密钥长度来加密和解密消息。每个密码分别使用 128,192 和 256 位的加密密钥以 128 位的块加密和解密数据。对称,也称为密钥,密码使用相同的密钥进行加密和解密,因此发送方和接收方必须都知道并使用相同的密钥。

例子

Java

// Java Program to Illustrate AES Encryption
 
// Importing required classes
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
 
// Main class
class GFG {
 
    // Encryption function
    // function 1
    public static void encryptEcb(String filenamePlain,
                                  String filenameEnc,
                                  byte[] key)
        throws IOException, NoSuchAlgorithmException,
               NoSuchPaddingException, InvalidKeyException,
               IllegalBlockSizeException,
               BadPaddingException
    {
 
        // Creating cipher instance OF AES encryption
        Cipher cipher
            = Cipher.getInstance("AES/ECB/PKCS5PADDING");
 
        // Specifying the algorithm
        SecretKeySpec secretKeySpec
            = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
 
        // Try block to check for exceptions
        try (FileInputStream fis
             = new FileInputStream(filenamePlain);
 
             // Creating objects of BufferedInputStream,
             // FileOutputStream and BufferedOutputStream
             BufferedInputStream inputstream
             = new BufferedInputStream(fis);
             FileOutputStream outputstream
             = new FileOutputStream(filenameEnc);
             BufferedOutputStream bufferedOutputStream
             = new BufferedOutputStream(outputstream)) {
 
            // Defining the buffer
            byte[] ibufffer = new byte[1024];
 
            int length;
 
            // Reading while read buffer has data
            while ((length = inputstream.read(ibufffer))
                   != -1) {
 
                // Creating cipher with buffer
                byte[] obuffer
                    = cipher.update(ibufffer, 0, length);
 
                if (obuffer != null)
 
                    // Writing encrypted text to buffer
                    bufferedOutputStream.write(obuffer);
            }
 
            byte[] obuffer = cipher.doFinal();
 
            if (obuffer != null)
                bufferedOutputStream.write(obuffer);
        }
    }
 
    // Method 3
    // Decryption method
    public static void decryptEcb(String filenameEnc,
                                  String filenameDec,
                                  byte[] key)
        throws IOException, NoSuchAlgorithmException,
               NoSuchPaddingException, InvalidKeyException,
               IllegalBlockSizeException,
               BadPaddingException
    {
 
        // Try block to check for exceptions
        try (FileInputStream inputStream
             = new FileInputStream(filenameEnc);
             FileOutputStream outputStream
             = new FileOutputStream(filenameDec)) {
            // Defining buffer
            byte[] ibuffer = new byte[1024];
            int length;
 
            // Creating cipher instance OF AES decryption
            Cipher cipher = Cipher.getInstance(
                "AES/ECB/PKCS5PADDING");
            SecretKeySpec secretKeySpec
                = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
 
            // While input stream not empty
            while ((length = inputStream.read(ibuffer))
                   != -1) {
 
                // Reading into the buffer
                byte[] obuffer
                    = cipher.update(ibuffer, 0, length);
                if (obuffer != null)
 
                    // Now writing to output buffer
                    outputStream.write(obuffer);
            }
 
            byte[] obuffer = cipher.doFinal();
            if (obuffer != null)
                outputStream.write(obuffer);
        }
    }
 
    // Method 3
    // Main driver method
    public static void main(String[] args)
        throws IOException, NoSuchPaddingException,
               NoSuchAlgorithmException, BadPaddingException
               ,
               IllegalBlockSizeException,
               InvalidKeyException
    {
 
        // Display message
        System.out.println("/****AES Encryption*******/");
 
        // Placing the PDF path
        String pFileName
            = "/home/aniket/IdeaProjects/Gfg Programs/MAD FINAL.pdf";
        String cFileName = "your pdf.enc";
 
        // Placing the PDF name
        String decFileName = "your pdf.pdf";
 
        // Creating cipher key 56 bit key length
        byte[] cipher_key
            = "12345678901234561234567890123456".getBytes(
                "UTF-8");
        encryptEcb(pFileName, cFileName, cipher_key);
        decryptEcb(cFileName, decFileName, cipher_key);
 
        // Print and display the file credentials
        System.out.println(
            "file of encryption: " + pFileName + "\n"
            + "created encrypted file  : " + cFileName
            + "\n"
            + "created decrypted file  : " + decFileName);
    }
}

输出:

/****AES Encryption*******/
file of encryption: MAD FINAL.pdf
created encrypted file  : MAD FINAL.enc
created decrypted file  : MAD FINAL.pdf