In Linux, Java calls the OpenSSL command to encrypt data in memory.

Source: Internet
Author: User

Project requirements:

Use OpenSSL to encrypt a dynamic string and send the encrypted data to another system.

Problem:

After reading the help information of the OpenSSL ENC command, we found that the [in] parameter can only receive one file. After the file is encrypted, a new encrypted file is output. Does not receive strings as encryption objects.

The solution provided by the customer is to create a file on the disk, write the dynamic string into the file, then call OpenSSL ENC encryption, and then read the encrypted file, send encrypted data to another system. After this operation, the created files and the files output by OpenSSL are useless. You also need to delete these junk files.

Although feasible, concurrent access and file operations are troublesome.

Solution:

After several twists and turns, I finally found a elegant solution that does not involve concurrent access or file operations.

Summary:

Here, we will first have a deep understanding of the OpenSSL ENC parameters [in] and [out.

[In] the parameter receives a file as an encrypted object. In fact, it can also read data from standard input. By default, data is read from standard input.

[Out] The parameter outputs an encrypted file, which can also output encrypted data to the standard output device, and the default is standard output.

Note: Reading data from standard input is not simply entering an encrypted string after the [in] parameter. If you are interested, try it, if you enter a string directly after the [in] parameter, the system will not hesitate to tell you:"Encrypted string": no such file or directory

To read data from standard input, use the MPs queue command. "|". I will explain it later.

OK. The data input problem is fixed.

Because I do not want to involve file operations, I will output the encrypted data to the standard output, and thenProgramCapture the output stream and read the encrypted data.

The following describes the implementation process in detail.

Implementation:

First, we will give a brief introduction to pipeline commands. The basic format is command1.|
Command2

In short, the output of command1 is used as the input of command2. The premise is that command2 must be able to receive standard input.

Step 1: OpenSSL command implementation

 
Echo-e "{0}" | OpenSSL aes-128-cbc-e-kfile {1}-base64

1. {0} is the data to be encrypted. Because it is dynamic, I will replace it with the actual data before executing the command.

2. The "EHCO" command outputs the content in quotation marks to the standard output device. Pipeline command will be used here"|"Use the output of the [Echo] command as the input of the [OpenSSL] command.

Note: The function of the [-E] parameter is to output the content of quotation marks without escaping. Otherwise, if the encrypted data contains special characters, the command execution will fail.

3. If the command does not contain the out parameter, the execution result of the command is output to the standard output by default.

4. The [-kfile] parameter is an encrypted password, and it must also receive a file parameter. However, OpenSSL also provides a non-File Password parameter: [-k "encrypted password"]. The encrypted password is fixed. Therefore, the [-kefile] method is used here to facilitate the Administrator to modify the encrypted password in the future. {1} will also be replaced with the real password file name before executing the command. This is not the focus of this article. You can understand it.

Part 2: Calling shell commands in Java

/***** Data encryption processing ** @ Param data the data to be encrypted * @ Param commonkey encrypted password file name * @ return encrypted data */public static final synchronized string encryption (string data, string commonkey) {// the encrypted data definition string encryptiondata = ""; try {// encryption command string encryption = "echo-e \" {0} \ "| OpenSSL aes-128-cbc-e-kfile {1}-base64 "; // Replace the placeholder encryption = messageformat in the command. format (encryption, Data, commonkey); string [] SH = new string [] {"/bin/sh", "-c", encryption }; // execute shell commandprocessbuilder Pb = new processbuilder (SH); process P = Pb. start (); encryptiondata = getshellout (p);} catch (exception e) {Throw new encryptionexception (E);} return encryptiondata ;}

Part 3: capture the output stream of shell commands in the Java program and read encrypted data

/*** Read output stream data ** @ Param p process * @ return the data read from the output stream * @ throws ioexception */public static final string getshellout (PROCESS p) throws ioexception {stringbuilder sb = new stringbuilder (); bufferedinputstream in = NULL; bufferedreader BR = NULL; try {In = new bufferedinputstream (P. getinputstream (); BR = new bufferedreader (New inputstreamreader (in); string s; while (S = BR. readline ())! = NULL) {// append the linefeed sb. append (constantutil. line_separator); sb. append (s) ;}} catch (ioexception e) {Throw e ;}finally {BR. close (); In. close ();} return sb. tostring ();}

So far, Java has completed calling the OpenSSL command to implement the memory encryption function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.