تقييم الموضوع:
  • 0 صوت - 0 بمعدل
  • 1
  • 2
  • 3
  • 4
  • 5
Encrypting a file line by line
#1
Encrypting a file line by line 
You can use a Bash loop to process the file line by line. This example uses 
How to run the script:
bash
كود:
./Encryptinglinebyline.sh /path/to/input_file.txt
bash
كود:
#!/bin/bash

#INPUT_FILE="/path/to/file.txt"

# Example: Read the file line by line  ./your_script.sh /path/to/input_file.txt

INPUT_FILE="$1"

# Check if file was provided and exists
if [ -z "$INPUT_FILE" ]; then
  echo "Usage: $0 <input_file>"
  exit 1
fi

if [ ! -f "$INPUT_FILE" ]; then
  echo "Error: File not found at $INPUT_FILE"
  exit 1
fi
OUTPUT_FILE="encrypted.txt"
PASSPHRASE="your_secret_password" # Replace with your actual password

> "$OUTPUT_FILE" # Clear the output file

while IFS= read -r line
do
  # Skip empty lines if necessary
  if [ -z "$line" ]; then
    continue
  fi
  # Encrypt the line and append to the output file
  echo "$line" | openssl enc -aes-256-cbc -a -salt -pbkdf2 -pass pass:"$PASSPHRASE" >> "$OUTPUT_FILE"
done < "$INPUT_FILE"

echo "Encryption complete. Encrypted data saved to $OUTPUT_FILE"
Decrypting the file line by line
The decryption process also involves reading each line of the encrypted file and decrypting it individually. 
bash
كود:
#!/bin/bash

#INPUT_FILE="/path/to/file_encrypted.txt"

# Example: Read the file line by line  ./your_script.sh /path/to/input_file.txt

INPUT_FILE="$1"

# Check if file was provided and exists
if [ -z "$INPUT_FILE" ]; then
  echo "Usage: $0 <input_file>"
  exit 1
fi

if [ ! -f "$INPUT_FILE" ]; then
  echo "Error: File not found at $INPUT_FILE"
  exit 1
fi
OUTPUT_FILE="decrypted.txt"
PASSPHRASE="your_secret_password" # Use the same password used for encryption

> "$OUTPUT_FILE" # Clear the output file

while IFS= read -r line
do
  # Decrypt the line and append to the output file
  echo "$line" | openssl enc -d -aes-256-cbc -a -salt -pbkdf2 -pass pass:"$PASSPHRASE" >> "$OUTPUT_FILE"
done < "$INPUT_FILE"

echo "Decryption complete. Decrypted data saved to $OUTPUT_FILE"
Alternative: Encrypting the entire file at once 
For most standard use cases, it is much simpler and more efficient to encrypt the entire file using a single OpenSSL command: 
[b]Encryption:[/b]
bash
كود:
openssl enc -aes-256-cbc -salt -pbkdf2 -a -e -in plaintext.txt -out encrypted.txt
[b]Decryption:[/b]
bash
كود:
openssl enc -d -aes-256-cbc -salt -pbkdf2 -a -in encrypted.txt -out decrypted.txt
الرد


الردود في هذا الموضوع
Encrypting a file line by line - بواسطة ftth - 11-04-2025, 08:52 AM

الانتقال السريع للمنتدى:


يتصفح هذا الموضوع من الأعضاء الان: بالاضافة الى ( 1 ) زائر