Encryption | #Encryption | simple way to encrypt and decrypt strings

 by   simbiose Java Updated: 9 months ago - 2.0.1 License: MIT

Download this library from

Build Applications

kandi X-RAY | Encryption REVIEW AND RATINGS

Encryption is a simple way to encrypt and decrypt strings on Android and Java project.

kandi-support
Support

  • Encryption has a low active ecosystem.
  • It has 327 star(s) with 81 fork(s).
  • It had no major release in the last 12 months.
  • On average issues are closed in 105 days.
  • It has a neutral sentiment in the developer community.

quality kandi
Quality

  • Encryption has no issues reported.

security
Security

  • Encryption has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.

license
License

  • Encryption is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.

build
Reuse

  • Encryption releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Encryption has no build file. You will be need to create the build yourself to build the component from source.
Top functions reviewed by kandi - BETA

kandi has reviewed Encryption and discovered the below as its top functions. This is intended to give you an instant insight into Encryption implemented functionality, and help decide if they suit your requirements.

  • Initializes the Encryption instance .
  • Demonstrates how to generate a custom Encryption usage .
  • Start the async usage
  • Method to decrypt data
  • Async encrypt string
  • Logs a message .
  • Encodes the given byte array as a string .
  • Main entry point .
  • Base64 encoding .

Encryption Key Features

What is Encryption library?

Encryption library is an Open Source library to help encryption routines in Android and Java applications, our target is to be simple and secure.

What is the "IV", what should be my yourByteIvArray

Encryption 1.2+ uses by default the AES algorithm in CBC mode, so to encrypt and decrypt works you should have the same key and the same IV byte array to encrypt and to decrypt. An example of IV is byte[] iv = {-89, -19, 17, -83, 86, 106, -31, 30, -5, -111, 61, -75, -84, 95, 120, -53}; like you can see, 16 bytes in a byte array. So if you want to use this library I recommend you create you own IV and save it :floppy_disk:.

I Don’t like null returns when errors occurs, what to do to handle errors?

You have the power to handle the exceptions, instead of uses encryptOrNull method just uses the encrypt method. The same for the decryptOrNull, just uses the decrypt method.

I’m getting problems with main thread, what to do?

Encrypt routines can take time, so you can uses the encryptAsync with a Encryption.Callback`to avoid ANR’S. The same for `decryptAsync

I’m an older user, version 1.4 or less, what to do to update Encrypt to version 2.+?

The library has changed the default iteration count from 65536 to 1, it improve the performance, if you have a code using the old version or if you prefer to use a big iteration count you just need to use a custom builder instead of get the default builder and set the iteration count you want

As far as the library uses 1 as default iteration count we do not need anymore the getLowIteration and it was removed from project, if you use it you can just change to getDefault

MIT is the project license so feel free to use it :tada:

I’m a very older user, version 1.1 or less, what to do to update Encrypt to version 1.2+?

The library has several changes in his structure in version 1.2, both in algorithm and in code usage, so if you are an older user you need migrate the encrypted stuff or configure the Builder manually to the same parameters used in version 1.1 and olds.

Copyright © 2010 The Android Open Source Project, applied to:

Base64 (third.part.android.util.Base64) original comes from [here](https://github.com/android/platform_frameworks_base/blob/ab69e29c1927bdc6143324eba5ccd78f7c43128d/core/java/android/util/Base64.java)

Encryption examples and code snippets

  • default
  • How to handle TLS handshake timeout in QTcpServer?
  • Error: "Driver [default] not supported." in laravel 8
  • Encrypt in JS front end and decrypt in python backend using AES GCM
  • Why do I get this error with phpmailer when trying to send an email?
  • Unable to mount EFS to ECS on fargate
  • Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set from Kafka rest proxy
  • Oracle SQL Encryption Using a Cell Value Password
  • How to encrypt any file no matter what type it is with Python?
  • PGPy throwing error when using BCPG public key
  • Bob and Alice asymmetric encryption and decryption implementation

default

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
  }
}

How to handle TLS handshake timeout in QTcpServer?

// We will have a handshake timeout of 30 seconds (same as firefox today)
QTimer::singleShot(30*1000, this, [this]() {

    // we use dynamic_cast because this may be or not an encrypted socket
    QSslSocket * const tlsSocket = dynamic_cast<QSslSocket*>(m_socket);

    if(tlsSocket != nullptr && !tlsSocket->isEncrypted()) {
        qWarning() << "TLS Handshake timeout for connection from " <<
                      tlsSocket->peerAddress().toString() << ":" << tlsSocket->peerPort();
        tlsSocket->close();
    }
});

Error: &quot;Driver [default] not supported.&quot; in laravel 8

/*
 |--------------------------------------------------------------------------
 | Session Database Connection
 |--------------------------------------------------------------------------
 |
 | When using the "database" or "redis" session drivers, you may specify a
 | connection that should be used to manage these sessions. This should
 | correspond to a connection in your database configuration options.
 |
 */

 'connection' => env('SESSION_CONNECTION', null),

Encrypt in JS front end and decrypt in python backend using AES GCM

from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
#import os

#key = AESGCM.generate_key(bit_length=256)    
#nonce = os.urandom(12)
key = base64.b64decode('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=') # fix for testing, AES-256
nonce = base64.b64decode('MDEyMzQ1Njc4OTAx') # fix for testing, 12 bytes

plaintext = b'The quick brown fox jumps over the lazy dog'
aad = b'the aad' # aad = None without additional authenticated data

aesgcm = AESGCM(key)
ciphertext = aesgcm.encrypt(nonce, plaintext, aad)
print('Ciphertext (B64): ' + base64.b64encode(ciphertext).decode('utf8'))
decrypted = aesgcm.decrypt(nonce, ciphertext, aad)
print('Decrypted:        ' + decrypted.decode('utf8'))
Output
Ciphertext (B64): JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Decrypted:        The quick brown fox jumps over the lazy dog
(async () => {      
    var key = Base64.toUint8Array('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE='); // fix for testing, AES-256
    var nonce = Base64.toUint8Array('MDEyMzQ1Njc4OTAx'); // fix for testing, 12 bytes

    var plaintext = new TextEncoder().encode("The quick brown fox jumps over the lazy dog");
    var aad = new TextEncoder().encode('the aad');
                
    var keyImported = await await crypto.subtle.importKey(
        "raw",
        key,
        { name: "AES-GCM" },
        true,
        ["decrypt", "encrypt"]
    );
                
    var ciphertext = await await crypto.subtle.encrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        plaintext
    );
    console.log('Ciphertext (Base64):\n', Base64.fromUint8Array(new Uint8Array(ciphertext)).replace(/(.{48})/g,'$1\n'));
              
    var decrypted = await await crypto.subtle.decrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        ciphertext
    );
    console.log('Plaintext:\n', new TextDecoder().decode(decrypted).replace(/(.{48})/g,'$1\n'));
})();
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js"></script>
Ciphertext (Base64):
 JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Plaintext:
 The quick brown fox jumps over the lazy dog
-----------------------
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
#import os

#key = AESGCM.generate_key(bit_length=256)    
#nonce = os.urandom(12)
key = base64.b64decode('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=') # fix for testing, AES-256
nonce = base64.b64decode('MDEyMzQ1Njc4OTAx') # fix for testing, 12 bytes

plaintext = b'The quick brown fox jumps over the lazy dog'
aad = b'the aad' # aad = None without additional authenticated data

aesgcm = AESGCM(key)
ciphertext = aesgcm.encrypt(nonce, plaintext, aad)
print('Ciphertext (B64): ' + base64.b64encode(ciphertext).decode('utf8'))
decrypted = aesgcm.decrypt(nonce, ciphertext, aad)
print('Decrypted:        ' + decrypted.decode('utf8'))
Output
Ciphertext (B64): JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Decrypted:        The quick brown fox jumps over the lazy dog
(async () => {      
    var key = Base64.toUint8Array('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE='); // fix for testing, AES-256
    var nonce = Base64.toUint8Array('MDEyMzQ1Njc4OTAx'); // fix for testing, 12 bytes

    var plaintext = new TextEncoder().encode("The quick brown fox jumps over the lazy dog");
    var aad = new TextEncoder().encode('the aad');
                
    var keyImported = await await crypto.subtle.importKey(
        "raw",
        key,
        { name: "AES-GCM" },
        true,
        ["decrypt", "encrypt"]
    );
                
    var ciphertext = await await crypto.subtle.encrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        plaintext
    );
    console.log('Ciphertext (Base64):\n', Base64.fromUint8Array(new Uint8Array(ciphertext)).replace(/(.{48})/g,'$1\n'));
              
    var decrypted = await await crypto.subtle.decrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        ciphertext
    );
    console.log('Plaintext:\n', new TextDecoder().decode(decrypted).replace(/(.{48})/g,'$1\n'));
})();
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js"></script>
Ciphertext (Base64):
 JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Plaintext:
 The quick brown fox jumps over the lazy dog
-----------------------
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
#import os

#key = AESGCM.generate_key(bit_length=256)    
#nonce = os.urandom(12)
key = base64.b64decode('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=') # fix for testing, AES-256
nonce = base64.b64decode('MDEyMzQ1Njc4OTAx') # fix for testing, 12 bytes

plaintext = b'The quick brown fox jumps over the lazy dog'
aad = b'the aad' # aad = None without additional authenticated data

aesgcm = AESGCM(key)
ciphertext = aesgcm.encrypt(nonce, plaintext, aad)
print('Ciphertext (B64): ' + base64.b64encode(ciphertext).decode('utf8'))
decrypted = aesgcm.decrypt(nonce, ciphertext, aad)
print('Decrypted:        ' + decrypted.decode('utf8'))
Output
Ciphertext (B64): JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Decrypted:        The quick brown fox jumps over the lazy dog
(async () => {      
    var key = Base64.toUint8Array('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE='); // fix for testing, AES-256
    var nonce = Base64.toUint8Array('MDEyMzQ1Njc4OTAx'); // fix for testing, 12 bytes

    var plaintext = new TextEncoder().encode("The quick brown fox jumps over the lazy dog");
    var aad = new TextEncoder().encode('the aad');
                
    var keyImported = await await crypto.subtle.importKey(
        "raw",
        key,
        { name: "AES-GCM" },
        true,
        ["decrypt", "encrypt"]
    );
                
    var ciphertext = await await crypto.subtle.encrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        plaintext
    );
    console.log('Ciphertext (Base64):\n', Base64.fromUint8Array(new Uint8Array(ciphertext)).replace(/(.{48})/g,'$1\n'));
              
    var decrypted = await await crypto.subtle.decrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        ciphertext
    );
    console.log('Plaintext:\n', new TextDecoder().decode(decrypted).replace(/(.{48})/g,'$1\n'));
})();
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js"></script>
Ciphertext (Base64):
 JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Plaintext:
 The quick brown fox jumps over the lazy dog
-----------------------
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
#import os

#key = AESGCM.generate_key(bit_length=256)    
#nonce = os.urandom(12)
key = base64.b64decode('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=') # fix for testing, AES-256
nonce = base64.b64decode('MDEyMzQ1Njc4OTAx') # fix for testing, 12 bytes

plaintext = b'The quick brown fox jumps over the lazy dog'
aad = b'the aad' # aad = None without additional authenticated data

aesgcm = AESGCM(key)
ciphertext = aesgcm.encrypt(nonce, plaintext, aad)
print('Ciphertext (B64): ' + base64.b64encode(ciphertext).decode('utf8'))
decrypted = aesgcm.decrypt(nonce, ciphertext, aad)
print('Decrypted:        ' + decrypted.decode('utf8'))
Output
Ciphertext (B64): JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Decrypted:        The quick brown fox jumps over the lazy dog
(async () => {      
    var key = Base64.toUint8Array('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE='); // fix for testing, AES-256
    var nonce = Base64.toUint8Array('MDEyMzQ1Njc4OTAx'); // fix for testing, 12 bytes

    var plaintext = new TextEncoder().encode("The quick brown fox jumps over the lazy dog");
    var aad = new TextEncoder().encode('the aad');
                
    var keyImported = await await crypto.subtle.importKey(
        "raw",
        key,
        { name: "AES-GCM" },
        true,
        ["decrypt", "encrypt"]
    );
                
    var ciphertext = await await crypto.subtle.encrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        plaintext
    );
    console.log('Ciphertext (Base64):\n', Base64.fromUint8Array(new Uint8Array(ciphertext)).replace(/(.{48})/g,'$1\n'));
              
    var decrypted = await await crypto.subtle.decrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        ciphertext
    );
    console.log('Plaintext:\n', new TextDecoder().decode(decrypted).replace(/(.{48})/g,'$1\n'));
})();
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js"></script>
Ciphertext (Base64):
 JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Plaintext:
 The quick brown fox jumps over the lazy dog
-----------------------
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
#import os

#key = AESGCM.generate_key(bit_length=256)    
#nonce = os.urandom(12)
key = base64.b64decode('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=') # fix for testing, AES-256
nonce = base64.b64decode('MDEyMzQ1Njc4OTAx') # fix for testing, 12 bytes

plaintext = b'The quick brown fox jumps over the lazy dog'
aad = b'the aad' # aad = None without additional authenticated data

aesgcm = AESGCM(key)
ciphertext = aesgcm.encrypt(nonce, plaintext, aad)
print('Ciphertext (B64): ' + base64.b64encode(ciphertext).decode('utf8'))
decrypted = aesgcm.decrypt(nonce, ciphertext, aad)
print('Decrypted:        ' + decrypted.decode('utf8'))
Output
Ciphertext (B64): JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Decrypted:        The quick brown fox jumps over the lazy dog
(async () => {      
    var key = Base64.toUint8Array('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE='); // fix for testing, AES-256
    var nonce = Base64.toUint8Array('MDEyMzQ1Njc4OTAx'); // fix for testing, 12 bytes

    var plaintext = new TextEncoder().encode("The quick brown fox jumps over the lazy dog");
    var aad = new TextEncoder().encode('the aad');
                
    var keyImported = await await crypto.subtle.importKey(
        "raw",
        key,
        { name: "AES-GCM" },
        true,
        ["decrypt", "encrypt"]
    );
                
    var ciphertext = await await crypto.subtle.encrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        plaintext
    );
    console.log('Ciphertext (Base64):\n', Base64.fromUint8Array(new Uint8Array(ciphertext)).replace(/(.{48})/g,'$1\n'));
              
    var decrypted = await await crypto.subtle.decrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        ciphertext
    );
    console.log('Plaintext:\n', new TextDecoder().decode(decrypted).replace(/(.{48})/g,'$1\n'));
})();
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js"></script>
Ciphertext (Base64):
 JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Plaintext:
 The quick brown fox jumps over the lazy dog

Why do I get this error with phpmailer when trying to send an email?

$mail->Host       = 'smpt.gmail.com';
$mail->Host       = 'smtp.gmail.com';
-----------------------
$mail->Host       = 'smpt.gmail.com';
$mail->Host       = 'smtp.gmail.com';

Unable to mount EFS to ECS on fargate

resource "aws_efs_access_point" this  {
  file_system_id = aws_efs_file_system.efs.id
  root_directory {
    path = "/desired-directory"
    creation_info {
      owner_gid = 0
      owner_uid = 0
      permissions = "755"
    }
  }
}

Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set from Kafka rest proxy

zookeeper.connect=z-3.msk.xxxx.xx.xxxxxx-1.amazonaws.com:2181,z-1.msk.xxxx.xx.xxxxxx-1.amazonaws.com:2181
bootstrap.servers=b-1.msk.xxxx.xx.xxxxxx-1.amazonaws.com:9096,b-2.msk.xxxx.xx.xxxxxx-1.amazonaws.com:9096
client.sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="username" password="username";
client.security.protocol=SASL_SSL
client.sasl.mechanism=SCRAM-SHA-512

Oracle SQL Encryption Using a Cell Value Password

CREATE OR REPLACE PACKAGE otherdata_encrypt_decrypt
AS
   FUNCTION encrypt (p_plainText VARCHAR2,p_password VARCHAR2) RETURN RAW DETERMINISTIC;
   FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC;
END;
/

CREATE OR REPLACE PACKAGE BODY otherdata_encrypt_decrypt
AS
     encryption_type    PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                                     + DBMS_CRYPTO.CHAIN_ECB
                                     + DBMS_CRYPTO.PAD_PKCS5;

   /* Input plaintext to encrypt with the given key in the package */
    
     
     FUNCTION encrypt (p_plainText VARCHAR2, p_password VARCHAR2) RETURN RAW DETERMINISTIC
     IS
        encrypted_raw      RAW (2000);

    /* The encryption or decryption on VARCHAR2 doesn't work directly using   DBMS_CRYPTO, therefore, convert input to RAW before encrypting it */

     BEGIN
        encrypted_raw := DBMS_CRYPTO.ENCRYPT
        
        (
           src => UTL_RAW.CAST_TO_RAW (p_plainText),
           typ => encryption_type,
           /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
           key => UTL_RAW.cast_to_raw(LPAD(p_password,32,'A'))
        );
       RETURN encrypted_raw;
     END encrypt;


     FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC
     IS
        decrypted_raw      RAW (2000);
     BEGIN
        decrypted_raw := DBMS_CRYPTO.DECRYPT
        
        (
            src => p_encryptedText,
            typ => encryption_type,
            /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
            key => UTL_RAW.cast_to_raw (LPAD(p_password,32,'A'))
        );
        RETURN (UTL_RAW.CAST_TO_VARCHAR2 (decrypted_raw));
     END decrypt;
END;
create or replace PROCEDURE CUSTOMERDEPT.insert_encrypt
(p_customer_id in customer.customer_id%TYPE,
p_customer_name in customer.customer_name%TYPE,
p_contact_number in customer.contact_number%TYPE,
p_credit_card_number in customer.credit_card_number%TYPE,
p_income in customer.income%TYPE,
p_password in customer.password%TYPE)
    IS
    
        encrypt_credit_card_no RAW(200);
        encrypt_income RAW(200);
        p_password_encrypt RAW(200);
        
        BEGIN
            
            encrypt_credit_card_no:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_credit_card_number,p_password);
            encrypt_income:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_income,p_password);
            p_password_encrypt:=SYS.ENCRYPT_DECRYPT.ENCRYPT(p_password);
        
            INSERT INTO customer(customer_id, customer_name, contact_number, credit_card_number, income, password)
            VALUES (p_customer_id,p_customer_name,p_contact_number,encrypt_credit_card_no,encrypt_income,p_password_encrypt);
            COMMIT;
    END;
EXEC insert_encrypt (7, Test123, 0777712345, '11112223334455', '2222.22', '122122')
-----------------------
CREATE OR REPLACE PACKAGE otherdata_encrypt_decrypt
AS
   FUNCTION encrypt (p_plainText VARCHAR2,p_password VARCHAR2) RETURN RAW DETERMINISTIC;
   FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC;
END;
/

CREATE OR REPLACE PACKAGE BODY otherdata_encrypt_decrypt
AS
     encryption_type    PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                                     + DBMS_CRYPTO.CHAIN_ECB
                                     + DBMS_CRYPTO.PAD_PKCS5;

   /* Input plaintext to encrypt with the given key in the package */
    
     
     FUNCTION encrypt (p_plainText VARCHAR2, p_password VARCHAR2) RETURN RAW DETERMINISTIC
     IS
        encrypted_raw      RAW (2000);

    /* The encryption or decryption on VARCHAR2 doesn't work directly using   DBMS_CRYPTO, therefore, convert input to RAW before encrypting it */

     BEGIN
        encrypted_raw := DBMS_CRYPTO.ENCRYPT
        
        (
           src => UTL_RAW.CAST_TO_RAW (p_plainText),
           typ => encryption_type,
           /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
           key => UTL_RAW.cast_to_raw(LPAD(p_password,32,'A'))
        );
       RETURN encrypted_raw;
     END encrypt;


     FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC
     IS
        decrypted_raw      RAW (2000);
     BEGIN
        decrypted_raw := DBMS_CRYPTO.DECRYPT
        
        (
            src => p_encryptedText,
            typ => encryption_type,
            /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
            key => UTL_RAW.cast_to_raw (LPAD(p_password,32,'A'))
        );
        RETURN (UTL_RAW.CAST_TO_VARCHAR2 (decrypted_raw));
     END decrypt;
END;
create or replace PROCEDURE CUSTOMERDEPT.insert_encrypt
(p_customer_id in customer.customer_id%TYPE,
p_customer_name in customer.customer_name%TYPE,
p_contact_number in customer.contact_number%TYPE,
p_credit_card_number in customer.credit_card_number%TYPE,
p_income in customer.income%TYPE,
p_password in customer.password%TYPE)
    IS
    
        encrypt_credit_card_no RAW(200);
        encrypt_income RAW(200);
        p_password_encrypt RAW(200);
        
        BEGIN
            
            encrypt_credit_card_no:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_credit_card_number,p_password);
            encrypt_income:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_income,p_password);
            p_password_encrypt:=SYS.ENCRYPT_DECRYPT.ENCRYPT(p_password);
        
            INSERT INTO customer(customer_id, customer_name, contact_number, credit_card_number, income, password)
            VALUES (p_customer_id,p_customer_name,p_contact_number,encrypt_credit_card_no,encrypt_income,p_password_encrypt);
            COMMIT;
    END;
EXEC insert_encrypt (7, Test123, 0777712345, '11112223334455', '2222.22', '122122')
-----------------------
CREATE OR REPLACE PACKAGE otherdata_encrypt_decrypt
AS
   FUNCTION encrypt (p_plainText VARCHAR2,p_password VARCHAR2) RETURN RAW DETERMINISTIC;
   FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC;
END;
/

CREATE OR REPLACE PACKAGE BODY otherdata_encrypt_decrypt
AS
     encryption_type    PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                                     + DBMS_CRYPTO.CHAIN_ECB
                                     + DBMS_CRYPTO.PAD_PKCS5;

   /* Input plaintext to encrypt with the given key in the package */
    
     
     FUNCTION encrypt (p_plainText VARCHAR2, p_password VARCHAR2) RETURN RAW DETERMINISTIC
     IS
        encrypted_raw      RAW (2000);

    /* The encryption or decryption on VARCHAR2 doesn't work directly using   DBMS_CRYPTO, therefore, convert input to RAW before encrypting it */

     BEGIN
        encrypted_raw := DBMS_CRYPTO.ENCRYPT
        
        (
           src => UTL_RAW.CAST_TO_RAW (p_plainText),
           typ => encryption_type,
           /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
           key => UTL_RAW.cast_to_raw(LPAD(p_password,32,'A'))
        );
       RETURN encrypted_raw;
     END encrypt;


     FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC
     IS
        decrypted_raw      RAW (2000);
     BEGIN
        decrypted_raw := DBMS_CRYPTO.DECRYPT
        
        (
            src => p_encryptedText,
            typ => encryption_type,
            /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
            key => UTL_RAW.cast_to_raw (LPAD(p_password,32,'A'))
        );
        RETURN (UTL_RAW.CAST_TO_VARCHAR2 (decrypted_raw));
     END decrypt;
END;
create or replace PROCEDURE CUSTOMERDEPT.insert_encrypt
(p_customer_id in customer.customer_id%TYPE,
p_customer_name in customer.customer_name%TYPE,
p_contact_number in customer.contact_number%TYPE,
p_credit_card_number in customer.credit_card_number%TYPE,
p_income in customer.income%TYPE,
p_password in customer.password%TYPE)
    IS
    
        encrypt_credit_card_no RAW(200);
        encrypt_income RAW(200);
        p_password_encrypt RAW(200);
        
        BEGIN
            
            encrypt_credit_card_no:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_credit_card_number,p_password);
            encrypt_income:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_income,p_password);
            p_password_encrypt:=SYS.ENCRYPT_DECRYPT.ENCRYPT(p_password);
        
            INSERT INTO customer(customer_id, customer_name, contact_number, credit_card_number, income, password)
            VALUES (p_customer_id,p_customer_name,p_contact_number,encrypt_credit_card_no,encrypt_income,p_password_encrypt);
            COMMIT;
    END;
EXEC insert_encrypt (7, Test123, 0777712345, '11112223334455', '2222.22', '122122')

How to encrypt any file no matter what type it is with Python?

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)

with open(filename, "rb") as file:
    file_data = file.read()
    encrypted_data = f.encrypt(file_data)

with open(filename, "wb") as file:
    file.write(encrypted_data)

PGPy throwing error when using BCPG public key

gpg: armor header: Version: BCPG v1.58
# off=0 ctb=98 tag=6 hlen=2 plen=141
:public key packet:
        version 4, algo 1, created 1512279161, expires 0
        pkey[0]: 8982110527490E7879EFA69E400DB23CAF666D90B02D6C188044A66C896E1DB15AE96E27F2954C8512A9B90B384AB808E225CC6D1F86EAEE51604CDBE00D6B3AB98E4C4BAD89875F803003643A8EF777C44F01D6E563A93D1310AC99B660707AC12CC14C5BFAF3B054B756297A5CC925ED2108682960145731BB7B9B846B0C97
        pkey[1]: 010001
        keyid: 9824BDE2E0C3C7D9
# off=143 ctb=b4 tag=13 hlen=2 plen=5
:user ID packet: "anish"
# off=150 ctb=88 tag=2 hlen=2 plen=156
:signature packet: algo 1, keyid 9824BDE2E0C3C7D9
        version 4, created 1512279161, md5len 0, sigclass 0x10
        digest algo 2, begin of digest 47 7b
        hashed subpkt 2 len 4 (sig created 2017-12-03)
        subpkt 16 len 8 (issuer key ID 9824BDE2E0C3C7D9)
        data: 52DB129379728F91A71F2A131D9333FAC505A4595A9FB6A0A877FAA55D8F81D6FD38C0956AE33097D6E33D8F47487420FDADE04D0E6A36AF6DC62236E05B28D90DC047A5DC564DB04314BAA6B27D8A63E2D67A576AB0B066412058B5D62EE40B1E8C515877FDA2552A796ECF9304252752BD21BF39A424EFC75E8337B43042FF
gpg: armor header: Comment: Alice's OpenPGP certificate
gpg: armor header: Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html
# off=0 ctb=98 tag=6 hlen=2 plen=51
:public key packet:
        version 4, algo 22, created 1548158185, expires 0
        pkey[0]: 092B06010401DA470F01 ed25519 (1.3.6.1.4.1.11591.15.1)
        pkey[1]: 40AE35B0937140AB28856C504A4F84F35DC541A8F4C1DE09B3942FD46FB3B5BB5D
        keyid: F231550C4F47E38E
# off=53 ctb=b4 tag=13 hlen=2 plen=38
:user ID packet: "Alice Lovelace <alice@openpgp.example>"
# off=93 ctb=88 tag=2 hlen=2 plen=144
:signature packet: algo 22, keyid F231550C4F47E38E
        version 4, created 1571135290, md5len 0, sigclass 0x13
        digest algo 8, begin of digest e9 2b
        hashed subpkt 27 len 1 (key flags: 03)
        hashed subpkt 11 len 4 (pref-sym-algos: 9 8 7 2)
        hashed subpkt 21 len 5 (pref-hash-algos: 10 9 8 11 2)
        hashed subpkt 22 len 3 (pref-zip-algos: 2 3 1)
        hashed subpkt 30 len 1 (features: 01)
        hashed subpkt 23 len 1 (keyserver preferences: 80)
        hashed subpkt 33 len 21 (issuer fpr v4 EB85BB5FA33A75E15E944E63F231550C4F47E38E)
        hashed subpkt 2 len 4 (sig created 2019-10-15)
        subpkt 16 len 8 (issuer key ID F231550C4F47E38E)
        data: 039C7052A203A6B073AC77DA86B226698119CE772A6F6E6F90B5766AB61F6BBF
        data: 1DC0C2D2D0BE3C702C3BB3938754B54C2F51889B2F6B001F08F69066879DF202
# off=239 ctb=b8 tag=14 hlen=2 plen=56
:public sub key packet:
        version 4, algo 18, created 1548158185, expires 0
        pkey[0]: 0A2B060104019755010501 cv25519 (1.3.6.1.4.1.3029.1.5.1)
        pkey[1]: 4042FF0621ADAB493CE0A9B5C2A430D8322291562B42B32DB4DF1DEC13DF9EBE22
        pkey[2]: 03010807
        keyid: 4766F6B9D5F21EB6
# off=297 ctb=88 tag=2 hlen=2 plen=120
:signature packet: algo 22, keyid F231550C4F47E38E
        version 4, created 1548158185, md5len 0, sigclass 0x18
        digest algo 8, begin of digest 59 d0
        hashed subpkt 33 len 21 (issuer fpr v4 EB85BB5FA33A75E15E944E63F231550C4F47E38E)
        hashed subpkt 2 len 4 (sig created 2019-01-22)
        hashed subpkt 27 len 1 (key flags: 0C)
        subpkt 16 len 8 (issuer key ID F231550C4F47E38E)
        data: C51D4B3A4C8731ACD4ED1191635059B53343C9D439E0FDC0D6E3137CD1FB27D1
        data: DB62ABED59028DE0040B4F15493795F9016C9B3E79FE59ED5A4C185A19AF3A01
-----------------------
gpg: armor header: Version: BCPG v1.58
# off=0 ctb=98 tag=6 hlen=2 plen=141
:public key packet:
        version 4, algo 1, created 1512279161, expires 0
        pkey[0]: 8982110527490E7879EFA69E400DB23CAF666D90B02D6C188044A66C896E1DB15AE96E27F2954C8512A9B90B384AB808E225CC6D1F86EAEE51604CDBE00D6B3AB98E4C4BAD89875F803003643A8EF777C44F01D6E563A93D1310AC99B660707AC12CC14C5BFAF3B054B756297A5CC925ED2108682960145731BB7B9B846B0C97
        pkey[1]: 010001
        keyid: 9824BDE2E0C3C7D9
# off=143 ctb=b4 tag=13 hlen=2 plen=5
:user ID packet: "anish"
# off=150 ctb=88 tag=2 hlen=2 plen=156
:signature packet: algo 1, keyid 9824BDE2E0C3C7D9
        version 4, created 1512279161, md5len 0, sigclass 0x10
        digest algo 2, begin of digest 47 7b
        hashed subpkt 2 len 4 (sig created 2017-12-03)
        subpkt 16 len 8 (issuer key ID 9824BDE2E0C3C7D9)
        data: 52DB129379728F91A71F2A131D9333FAC505A4595A9FB6A0A877FAA55D8F81D6FD38C0956AE33097D6E33D8F47487420FDADE04D0E6A36AF6DC62236E05B28D90DC047A5DC564DB04314BAA6B27D8A63E2D67A576AB0B066412058B5D62EE40B1E8C515877FDA2552A796ECF9304252752BD21BF39A424EFC75E8337B43042FF
gpg: armor header: Comment: Alice's OpenPGP certificate
gpg: armor header: Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html
# off=0 ctb=98 tag=6 hlen=2 plen=51
:public key packet:
        version 4, algo 22, created 1548158185, expires 0
        pkey[0]: 092B06010401DA470F01 ed25519 (1.3.6.1.4.1.11591.15.1)
        pkey[1]: 40AE35B0937140AB28856C504A4F84F35DC541A8F4C1DE09B3942FD46FB3B5BB5D
        keyid: F231550C4F47E38E
# off=53 ctb=b4 tag=13 hlen=2 plen=38
:user ID packet: "Alice Lovelace <alice@openpgp.example>"
# off=93 ctb=88 tag=2 hlen=2 plen=144
:signature packet: algo 22, keyid F231550C4F47E38E
        version 4, created 1571135290, md5len 0, sigclass 0x13
        digest algo 8, begin of digest e9 2b
        hashed subpkt 27 len 1 (key flags: 03)
        hashed subpkt 11 len 4 (pref-sym-algos: 9 8 7 2)
        hashed subpkt 21 len 5 (pref-hash-algos: 10 9 8 11 2)
        hashed subpkt 22 len 3 (pref-zip-algos: 2 3 1)
        hashed subpkt 30 len 1 (features: 01)
        hashed subpkt 23 len 1 (keyserver preferences: 80)
        hashed subpkt 33 len 21 (issuer fpr v4 EB85BB5FA33A75E15E944E63F231550C4F47E38E)
        hashed subpkt 2 len 4 (sig created 2019-10-15)
        subpkt 16 len 8 (issuer key ID F231550C4F47E38E)
        data: 039C7052A203A6B073AC77DA86B226698119CE772A6F6E6F90B5766AB61F6BBF
        data: 1DC0C2D2D0BE3C702C3BB3938754B54C2F51889B2F6B001F08F69066879DF202
# off=239 ctb=b8 tag=14 hlen=2 plen=56
:public sub key packet:
        version 4, algo 18, created 1548158185, expires 0
        pkey[0]: 0A2B060104019755010501 cv25519 (1.3.6.1.4.1.3029.1.5.1)
        pkey[1]: 4042FF0621ADAB493CE0A9B5C2A430D8322291562B42B32DB4DF1DEC13DF9EBE22
        pkey[2]: 03010807
        keyid: 4766F6B9D5F21EB6
# off=297 ctb=88 tag=2 hlen=2 plen=120
:signature packet: algo 22, keyid F231550C4F47E38E
        version 4, created 1548158185, md5len 0, sigclass 0x18
        digest algo 8, begin of digest 59 d0
        hashed subpkt 33 len 21 (issuer fpr v4 EB85BB5FA33A75E15E944E63F231550C4F47E38E)
        hashed subpkt 2 len 4 (sig created 2019-01-22)
        hashed subpkt 27 len 1 (key flags: 0C)
        subpkt 16 len 8 (issuer key ID F231550C4F47E38E)
        data: C51D4B3A4C8731ACD4ED1191635059B53343C9D439E0FDC0D6E3137CD1FB27D1
        data: DB62ABED59028DE0040B4F15493795F9016C9B3E79FE59ED5A4C185A19AF3A01

Bob and Alice asymmetric encryption and decryption implementation

void Main()
{
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    string publicKey = rsa.ToXmlString(false);
    string privateKey = rsa.ToXmlString(true);
    
    EncryptText(publicKey, "Test", @"d:\temp\test.dat");
    Console.WriteLine(DecryptData(privateKey, @"d:\temp\test.dat"));
}

COMMUNITY DISCUSSIONS

Top Trending Discussions on Encryption
  • How to handle TLS handshake timeout in QTcpServer?
  • Error: &quot;Driver [default] not supported.&quot; in laravel 8
  • Encrypt in JS front end and decrypt in python backend using AES GCM
  • SwiftUI / iOS / iPhone how to encrypt data/ image before storing and where / how to store locally, general best practice?
  • Why do I get this error with phpmailer when trying to send an email?
  • Unable to mount EFS to ECS on fargate
  • Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set from Kafka rest proxy
  • Oracle SQL Encryption Using a Cell Value Password
  • How to encrypt any file no matter what type it is with Python?
  • PGPy throwing error when using BCPG public key
Top Trending Discussions on Encryption

QUESTION

How to handle TLS handshake timeout in QTcpServer?

Asked 2021-Jun-15 at 10:02

I'm trying to figure out how to create a timeout for the handshake process in a TLS connection in a QTcpServer.

I tried something like this in the overriden incomingConnection function:

QSslSocket * const tlsSocket = static_cast<QSslSocket*>(socket);
    connect(tlsSocket, &QSslSocket::encrypted, this, [this, tlsSocket](){ addPendingConnection(tlsSocket); });
    tlsSocket->setLocalCertificate(m_serverCertificate);
    tlsSocket->setPrivateKey(m_serverPrivateKey);
    tlsSocket->setProtocol(QSsl::SecureProtocols);
    tlsSocket->startServerEncryption();

    // We will have a handshake timeout of 30 seconds
    QTimer::singleShot(30*1000, this, [this, tlsSocket]() {
        if(!tlsSocket->isEncrypted()) {
            // If no handshake initialized from the client close the connection
            delete tlsSocket;
        }
    });

But this doesn't seem to work because I am not calling directly addPendingConnection function (it get's called in a slot/lamdba which seems to break the pendingConnection chain.

Does anybody know how can I achieve this timeout in Qt? The problem at the moment is that a client can open a connection with the server and it never answers the TLS handshake which leads to an useless open connection (that is never closed).

ANSWER

Answered 2021-Jun-15 at 10:02

I ended implementing the TLS handshake timeout this way:

// We will have a handshake timeout of 30 seconds (same as firefox today)
QTimer::singleShot(30*1000, this, [this]() {

    // we use dynamic_cast because this may be or not an encrypted socket
    QSslSocket * const tlsSocket = dynamic_cast<QSslSocket*>(m_socket);

    if(tlsSocket != nullptr && !tlsSocket->isEncrypted()) {
        qWarning() << "TLS Handshake timeout for connection from " <<
                      tlsSocket->peerAddress().toString() << ":" << tlsSocket->peerPort();
        tlsSocket->close();
    }
});

This code can be added anywhere where is more practical for your project. I added it in a session class that we have (which owns the created socket), this class is created in the end of newConnection slot. I have tested it and works perfectly.

Source https://stackoverflow.com/questions/67838190

QUESTION

Error: &quot;Driver [default] not supported.&quot; in laravel 8

Asked 2021-Jun-14 at 23:09

I don't really know where the error is, for me, it's still a mystery. But I'm using Laravel 8 to produce a project, it was working perfectly and randomly started to return this error and all projects started to return this error too. I believe it's something with Redis, as I'm using it to store the system cache. When I go to access my endpoint in postman it returns the following error:

InvalidArgumentException: Driver [default] not supported. in file /var/www/vendor/laravel/framework/src/Illuminate/Support/Manager.php on line 109

#0 /var/www/vendor/laravel/framework/src/Illuminate/Support/Manager.php(80): Illuminate\Support\Manager->createDriver('default')
#1 /var/www/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(159): Illuminate\Support\Manager->driver()
#2 /var/www/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(57): Illuminate\Session\Middleware\StartSession->getSession(Object(Illuminate\Http\Request))
#3 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#4 /var/www/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#5 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#6 /var/www/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(67): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#7 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#8 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#9 /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php(695): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#10 /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php(670): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#11 /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php(636): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#12 /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php(625): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#13 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(166): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#14 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#15 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#16 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#17 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#18 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#19 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#20 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#21 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#22 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance->handle(Object(Illuminate\Http\Request), Object(Closure))
#23 /var/www/vendor/fruitcake/laravel-cors/src/HandleCors.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#24 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\Cors\HandleCors->handle(Object(Illuminate\Http\Request), Object(Closure))
#25 /var/www/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#26 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#27 /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#28 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(141): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#29 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(110): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#30 /var/www/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#31 {main}

When I access this same endpoint in the browser, it returns this other error:

InvalidArgumentException
Driver [default] not supported.

vendor/laravel/framework/src/Illuminate/Support/Manager.php:109

    protected function createDriver($driver) {
        // First, we will determine if a custom driver creator exists for the given driver and

        // if it does not we will check for a creator method for the driver. Custom creator
        // callbacks allow developers to build their own "drivers" easily using Closures.
        if (isset($this->customCreators[$driver])) {
            return $this->callCustomCreator($driver);
        } else {
            $method = 'create'.Str::studly($driver).'Driver';
            if (method_exists($this, $method)) {
                return $this->$method();
            }
        }
        throw new InvalidArgumentException("Driver [$driver] not supported.");
    }

    /**
     * Call a custom driver creator.
     *
     * @param  string  $driver
     * @return mixed
     */

    protected function callCustomCreator($driver) {
        return $this->customCreators[$driver]($this->container);
    }

    /**
     * Register a custom driver creator Closure.

As I'm not sure where the error is, I'm not sure which part of the code I could put here, but if someone has already gotten an error like that, help me. I'm totally lost.

In my .env file I declared the

 SESSION_CONNECTION=session
 BROADCAST_DRIVER=log
 CACHE_DRIVER=redis
 REDIS_URL=redis
 QUEUE_CONNECTION=sync
 SESSION_DRIVER=redis
 SESSION_LIFETIME=126
 SESSION_CONNECTION=session
 MEMCACHED_HOST=127.0.0.1
 REDIS_HOST=redis
 REDIS_PASSWORD=null
 REDIS_CLIENT = predis
 REDIS_PORT=6379

in my config\database.php file

<?php
use Illuminate\Support\Str;
return [
    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */
    'default' => env('DB_CONNECTION', 'mysql'),
    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections set up for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [
        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open-source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [
        'client' => env('REDIS_CLIENT', 'phpredis'),
        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],
        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '2'),
        ],
        'session' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => '1',
            'prefix' => 's:'
        ],
    ],
];

my config\session.php file

<?php
use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "dynamodb", "array"
    |
    */
    'driver' => env('SESSION_DRIVER', 'file'),

    /*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire on the browser closing, set that option.
    |
    */
    'lifetime' => env('SESSION_LIFETIME', 120),
    'expire_on_close' => false,

    /*
    |--------------------------------------------------------------------------
    | Session Encryption
    |--------------------------------------------------------------------------
    |
    | This option allows you to easily specify that all of your session data
    | should be encrypted before it is stored. All encryption will be run
    | automatically by Laravel and you can use the Session like normal.
    |
    */
    'encrypt' => false,

    /*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where the session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */
    'files' => storage_path('framework/sessions'),

    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "Redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */
    'connection' => env('SESSION_CONNECTION', null),

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */
    'table' => 'sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Cache-Store
    |--------------------------------------------------------------------------
    |
    | While using one of the framework's cache driven session backends you may
    | list a cache store that should be used for these sessions. This value
    | must match with one of the application's configured cache "stores".
    |
    | Affects: "apc", "dynamodb", "memcached", "redis"
    |
    */
    'store' => env('SESSION_STORE', null),

    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */
    'lottery' => [2, 100],

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Name
    |--------------------------------------------------------------------------
    |
    | Here you may change the name of the cookie used to identify a session
    | instance by ID. The name specified here will get used every time a
    | new session cookie is created by the framework for every driver.
    |
    */
    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Path
    |--------------------------------------------------------------------------
    |
    | The session cookie path determines the path for which the cookie will
    | be regarded as available. Typically, this will be the root path of
    | your application but you are free to change this when necessary.
    |
    */
    'path' => '/',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */
    'domain' => env('SESSION_DOMAIN', null),

    /*
    |--------------------------------------------------------------------------
    | HTTPS Only Cookies
    |--------------------------------------------------------------------------
    |
    | By setting this option to true, session cookies will only be sent back
    | to the server if the browser has an HTTPS connection. This will keep
    | the cookie from being sent to you if it can not be done securely.
    |
    */
    'secure' => env('SESSION_SECURE_COOKIE'),

    /*
    |--------------------------------------------------------------------------
    | HTTP Access Only
    |--------------------------------------------------------------------------
    |
    | Setting this value to true will prevent JavaScript from accessing the
    | value of the cookie and the cookie will only be accessible through
    | the HTTP protocol. You are free to modify this option if needed.
    |
    */
    'http_only' => true,

    /*
    |--------------------------------------------------------------------------
    | Same-Site Cookies
    |--------------------------------------------------------------------------
    |
    | This option determines how your cookies behave when cross-site requests
    | take place and can be used to mitigate CSRF attacks. By default, we
    | will set this value to "lax" since this is a secure default value.
    |
    | Supported: "lax", "strict", "none", null
    |
    */
    'same_site' => 'lax',
];

ANSWER

Answered 2021-Jun-12 at 01:50

Your problem is that you have set SESSION_CONNECTION=session, but your SESSION_DRIVER=default, so you have to use SESSION_DRIVER=database in your .env. See the config/session.php:

/*
 |--------------------------------------------------------------------------
 | Session Database Connection
 |--------------------------------------------------------------------------
 |
 | When using the "database" or "redis" session drivers, you may specify a
 | connection that should be used to manage these sessions. This should
 | correspond to a connection in your database configuration options.
 |
 */

 'connection' => env('SESSION_CONNECTION', null),

Source https://stackoverflow.com/questions/67944667

QUESTION

Encrypt in JS front end and decrypt in python backend using AES GCM

Asked 2021-Jun-14 at 18:01

I am trying encrypting in JS front end and decrypt in python backend using AES GCM cryptographic algorithm. I am using Web cryptography api for JS front end and python cryptography library for python backend as cryptographic library. I have fixed the IV for now in both side. I have implemented encryption-decryption code in both side, they work on each side. But I think the padding is done differently, can't seem to figure out how the padding is done in web cryptography api. Here is the encryption and decryption for the python backend:

def encrypt(derived_key, secret):
    IV = bytes("ddfbccae-b4c4-11", encoding="utf-8")
    aes = Cipher(algorithms.AES(derived_key), modes.GCM(IV))
    encryptor = aes.encryptor()
    padder = padding.PKCS7(128).padder()
    padded_data = padder.update(secret.encode()) + padder.finalize()
    return encryptor.update(padded_data) + encryptor.finalize()

def decrypt(derived_key, secret): 
    IV = bytes("ddfbccae-b4c4-11", encoding="utf-8")
    aes = Cipher(algorithms.AES(derived_key), modes.GCM(IV))
    decryptor = aes.decryptor()
    decrypted_data = decryptor.update(secret) 
    unpadder = padding.PKCS7(128).unpadder()
    return unpadder.update(decrypted_data) + unpadder.finalize()

Here's the JS code for encryption and decryption code:

async function encrypt(secretKey, message) {
  let iv = "ddfbccae-b4c4-11";
  iv = Uint8Array.from(iv, x => x.charCodeAt(0))
  let encoded = getMessageEncoding(message);
  ciphertext = await window.crypto.subtle.encrypt(
    {
      name: "AES-GCM",
      iv: iv
    },
    secretKey,
    encoded
  );
  return ciphertext;
}

async function decrypt(secretKey, cipherText) {
  iv = "ddfbccae-b4c4-11";
  iv = Uint8Array.from(iv, x => x.charCodeAt(0))
  try {
    let decrypted = await window.crypto.subtle.decrypt(
      {
        name: "AES-GCM",
        iv: iv
      },
      secretKey,
      cipherText
    );

    let dec = new TextDecoder();
    console.log("Decrypted message: ");
    console.log(dec.decode(decrypted));
   
  } catch (e) {
    console.log("error");
    
  }
}

I try to encrypt in the JS side and decrypt in the python side. But I got the following error: enter image description here

If I try to encrypt the same string in both side I got these outputs: In python the encrypted text: \x17O\xadn\x11*I\x94\x99\xc6\x90\x8a\xa9\x9cc=

In JS the encrypted text: \x17O\xadn\x11*I\xdf\xe3F\x81(\x15\xcc\x8c^z\xdf+\x1d\x91K\xbc

How to solve this padding issue?

ANSWER

Answered 2021-Jun-14 at 18:01

GCM is a stream cipher mode and therefore does not require padding. During encryption, an authentication tag is implicitly generated, which is used for authentication during decryption. Also, an IV/nonce of 12 bytes is recommended for GCM.

The posted Python code unnecessarily pads and doesn't take the authentication tag into account, unlike the JavaScript code, which may be the main reason for the different ciphertexts. Whether this is the only reason and whether the JavaScript code implements GCM correctly, is difficult to say, since the getMessageEncoding() method was not posted, so testing this was not possible.

Also, both codes apply a 16 bytes IV/nonce instead of the recommended 12 bytes IV/nonce.


Cryptography offers two possible implementations for GCM. One implementation uses the architecture of the non-authenticating modes like CBC. The posted Python code applies this design, but does not take authentication into account and therefore implements GCM incompletely. A correct example for this design can be found here.
Cryptography generally recommends the other approach for GCM (s. the Danger note), namely the AESGCM class, which performs implicit authentication so that this cannot be accidentally forgotten or incorrectly implemented.

The following implementation uses the AESGCM class (and also takes into account the optional additional authenticated data):

from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
#import os

#key = AESGCM.generate_key(bit_length=256)    
#nonce = os.urandom(12)
key = base64.b64decode('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=') # fix for testing, AES-256
nonce = base64.b64decode('MDEyMzQ1Njc4OTAx') # fix for testing, 12 bytes

plaintext = b'The quick brown fox jumps over the lazy dog'
aad = b'the aad' # aad = None without additional authenticated data

aesgcm = AESGCM(key)
ciphertext = aesgcm.encrypt(nonce, plaintext, aad)
print('Ciphertext (B64): ' + base64.b64encode(ciphertext).decode('utf8'))
decrypted = aesgcm.decrypt(nonce, ciphertext, aad)
print('Decrypted:        ' + decrypted.decode('utf8'))

with the output:

Output
Ciphertext (B64): JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Decrypted:        The quick brown fox jumps over the lazy dog

The authentication tag is appended to the ciphertext, so the (Base64 decoded) result has the length of the plaintext (43 bytes) plus the length of the tag (16 bytes, default), giving a total of 59 bytes.

For testing, a predefined key and IV/nonce are used with regard to a comparison with the result of the JavaScript code. Note that in practice a key/IV pair may only be used once for security reasons, which is especially important for GCM mode, e.g. here. Therefore a random IV/nonce is typically generated for each encryption.


The WebCrypto API is a low level API for cryptography and does not provide methods for Base64 encoding/decoding. In the following, js-base64 is used for simplicity. Just like the Python code, the tag is appended to the ciphertext.

A possible implementation for AES-GCM using the key and IV/nonce of the Python code that is functionally essentially the same as the posted JavaScript code is:

(async () => {      
    var key = Base64.toUint8Array('MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE='); // fix for testing, AES-256
    var nonce = Base64.toUint8Array('MDEyMzQ1Njc4OTAx'); // fix for testing, 12 bytes

    var plaintext = new TextEncoder().encode("The quick brown fox jumps over the lazy dog");
    var aad = new TextEncoder().encode('the aad');
                
    var keyImported = await await crypto.subtle.importKey(
        "raw",
        key,
        { name: "AES-GCM" },
        true,
        ["decrypt", "encrypt"]
    );
                
    var ciphertext = await await crypto.subtle.encrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        plaintext
    );
    console.log('Ciphertext (Base64):\n', Base64.fromUint8Array(new Uint8Array(ciphertext)).replace(/(.{48})/g,'$1\n'));
              
    var decrypted = await await crypto.subtle.decrypt(
        { name: "AES-GCM", iv: nonce, additionalData: aad }, // { name: "AES-GCM", iv: nonce } without additional authenticated data
        keyImported,
        ciphertext
    );
    console.log('Plaintext:\n', new TextDecoder().decode(decrypted).replace(/(.{48})/g,'$1\n'));
})();
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js"></script>

with the output:

Ciphertext (Base64):
 JOetStCANhPISvQ6G6IcRBauqbtC8fzRooblayHqkqSPKzLbidx/gBWfLNzBC+ZpcAGnGnHXaI7CB1U=
Plaintext:
 The quick brown fox jumps over the lazy dog

where the ciphertext is the same as that of the Python code.

Source https://stackoverflow.com/questions/67963529

QUESTION

SwiftUI / iOS / iPhone how to encrypt data/ image before storing and where / how to store locally, general best practice?

Asked 2021-Jun-14 at 06:58

I am new to SwiftUI (iOS App Ver 14.x) as I normally use Xamarin.

In this case I need to have the application specifically written in SwiftUI. (I am aware that some stuff still needs UIKit).

I have got my head around it though I am generally speaking struggling to get to grips with where and how to store stuff.

For example (greatly simplified) let us say I want the following:

All in the same view.

Two form fields:

First Name: … Last Name: …

A Button that says, “Add Photo”.

A Button that says, “Save Locally” (N/a but just for info, to be later uploaded to a web service that isn't always available at some point).

Now doing all the standard stuff this is pretty straight forward.

BUT.

I want to encrypt the form input (once converted to JSON, note I can convert to JSON easy enough).

I also want to encrypt the image before it is stored. (the real app has more than one image).

The stuff will be encrypted in the real app using asymmetric encryption (which I understand well, again this is not so relevant here).

But for the sake of example, I am happy to just ‘encrypt’ the JSON and picture as two separate files using something simple just to show the idea. XOR it or something simple to show.

My question is where is the best places code wise to do this with some basic examples if possible. I know this is a little subjective but just something simple and obvious. Click button, run this func, do this type of thing etc.

Where do I store stuff (which I am finding a bit all over the place)? This is my main source of confusion being honest.

My understanding is that you would use a FileManager object and the documents directory (though I am not sure if this is best practice, or even the right place.

The requirement from a client is that nothing is stored unencrypted for compliance reasons (completely ignoring anything Apple have in place good or bad).

ANSWER

Answered 2021-Jun-14 at 06:58

Yes you can just store it in the documents folder by using file manager:

FileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)[0]

As for encryption, if you encrypt the data before writing them to disk then they are encrypted...

One issue is that the encryption key has to be stored securely as well. For this, I usually generate the key when it is first used and store in keychain. Hard-coding the key in the code is not as secure because it makes the key identical for all users, and the binary can (not sure how easy) be reverse-engineered. We have to trust Apple's keychain to be secure. Some checks for jailbreaking may also help hear.

Also note that unlike other app data (UserDefaults, files etc), keychain is NOT cleared when the app is reinstalled!!! This can be a major source of headache. If desired, you can work around this by running a a chunk of code to clear the keychain when the app runs the first time after installation (by keeping a flag in UserDefaults, for example, which is cleared when app is reinstalled).

Source https://stackoverflow.com/questions/67963579

QUESTION

Why do I get this error with phpmailer when trying to send an email?

Asked 2021-Jun-13 at 17:15

Error:

2021-03-19 15:17:50 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP t24sm3903607qto.23 - gsmtp
2021-03-19 15:17:50 CLIENT -> SERVER: EHLO localhost
2021-03-19 15:17:50 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [24.233.165.10]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2021-03-19 15:17:50 CLIENT -> SERVER: STARTTLS
2021-03-19 15:17:50 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2021-03-19 15:17:50 CLIENT -> SERVER: EHLO localhost
2021-03-19 15:17:50 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [24.233.165.10]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2021-03-19 15:17:50 CLIENT -> SERVER: AUTH LOGIN
2021-03-19 15:17:50 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2021-03-19 15:17:50 CLIENT -> SERVER: [credentials hidden]
2021-03-19 15:17:50 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2021-03-19 15:17:50 CLIENT -> SERVER: [credentials hidden]
2021-03-19 15:17:51 SERVER -> CLIENT: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8 https://support.google.com/mail/?p=BadCredentials t24sm3903607qto.23 - gsmtp
2021-03-19 15:17:51 SMTP ERROR: Password command failed: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8 https://support.google.com/mail/?p=BadCredentials t24sm3903607qto.23 - gsmtp
SMTP Error: Could not authenticate.
2021-03-19 15:17:51 CLIENT -> SERVER: QUIT
2021-03-19 15:17:51 SERVER -> CLIENT: 221 2.0.0 closing connection t24sm3903607qto.23 - gsmtp
SMTP Error: Could not authenticate.
Message could not be sent. Mailer Error: SMTP Error: Could not authenticate.

My Code:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
 
require 'PHPMailer/PHPMailer/src/Exception.php';
require 'PHPMailer/PHPMailer/src/PHPMailer.php';
require 'PHPMailer/PHPMailer/src/SMTP.php';
 
// Instantiation and passing [ICODE]true[/ICODE] enables exceptions
$mail = new PHPMailer(true);
 
try {
    //Server settings
    $mail->SMTPDebug = 2;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'myemail@gmail.com';                     // SMTP username
    $mail->Password   = '*************';                               // SMTP password
    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, [ICODE]ssl[/ICODE] also accepted
    $mail->Port       = 587;                                    // TCP port to connect to
 
    //Recipients
    $mail->setFrom('myemail.com', 'Mailer');
    $mail->addAddress('myemail@gmail.com', 'Recipients');     // Add a recipient
    //$mail->addAddress('');
    $mail->addReplyTo('myemai@gmail.com', 'Mailer');
    //$mail->addCC('');
    //$mail->addBCC('');
 
    // Attachments
    //$mail->addAttachment('');         // Add attachments
    //$mail->addAttachment('');
 
    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
 
    $mail->send();
    echo 'Message has been sent';
 
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

I have less secure apps enabled. I have IMAP enabled. Two step verification off. I downloaded the latest version from github. The email is my email and does work. What should I do? I am trying this from my localhost on xampp. My password is correct. Why does this happen?

Less secure apps on

ANSWER

Answered 2021-Mar-19 at 15:15

It's this typo:

$mail->Host       = 'smpt.gmail.com';

That should be:

$mail->Host       = 'smtp.gmail.com';

The error message itself says that the host name could not be found, which is entirely expected given that it's wrong.

Source https://stackoverflow.com/questions/66710606

QUESTION

Unable to mount EFS to ECS on fargate

Asked 2021-Jun-13 at 14:30

trying to mount EFS to ECS Fargate but getting below error while task is being executed. it looks as though it is an IAM issue but crosschecked all the roles and unable to identify the issue. Checked security groups as well.i allowed 2049 port and attached ecs security group to it.

"ResourceInitializationError: failed to invoke EFS utils commands to set up EFS volumes: stderr: b'mount.nfs4: access denied by server while mounting 127.0.0.1:/' : unsuccessful EFS utils command execution; code: 32"

Terraform 0.12 and Fargate 1.4.0

resource "aws_efs_file_system" efs {
  creation_token   = "${var.prefix}-${var.appName}-ecs"
  encrypted        = true
  kms_key_id       = data.aws_kms_key.efs_kms_key.arn
  performance_mode = var.performance_mode
  throughput_mode  = var.throughput_mode
  tags            = var.tags
}


resource "aws_efs_mount_target" efs_mount {

  count           = length(module.vpc_presets.subnet_ids)
  file_system_id  = aws_efs_file_system.efs.id
  subnet_id       = flatten(module.vpc_presets.subnet_ids)[count.index]
  security_groups = data.terraform_remote_state.remote_state_sg.outputs.efs_sg

}
resource "aws_efs_access_point" this  {
  file_system_id = aws_efs_file_system.efs.id
}
data "template_file" jenkins_container_def {
  template = file("${path.module}/templates/jenkins.json.tpl")

  vars = {
    name                = "${var.prefix}-${var.appName}-${var.env}"
    jenkins_controller_port = var.jenkins_port
    jnlp_port           = var.jnlp_port
    source_volume       = "${var.appName}-efs"
    jenkins_home        = "/var/jenkins_home"
    container_image     = var.image
    region              = var.deployment_region
    account_id          = var.account
    log_group           = data.terraform_remote_state.remote_state_ecs.outputs.logs_name
    memory              = var.jenkins_memory
    cpu                 = var.jenkins_cpu
  }
}


resource "aws_ecs_task_definition" jenkins_controller {
  family = var.appName
  task_role_arn            = data.terraform_remote_state.remote_state_iam.outputs.master_task_arn
  execution_role_arn       = data.terraform_remote_state.remote_state_iam.outputs.jenkins_execution_arn
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu                      = var.jenkins_cpu
  memory                   = var.jenkins_memory
  container_definitions    = data.template_file.jenkins_container_def.rendered

  volume {
    name = "${var.appName}-efs"

    efs_volume_configuration {
      file_system_id     = data.terraform_remote_state.remote_state_efs.outputs.efs_fs_id
      transit_encryption = "ENABLED"

      authorization_config {
        access_point_id = flatten(data.terraform_remote_state.remote_state_efs.outputs.efs_access_point_id)[0]
        iam             = "ENABLED"
      }
    }
  }

  tags = var.tags
}

resource "aws_ecs_service" jenkins_controller {
  name = "${var.prefix}-${var.appName}-controller-service"

  task_definition  = aws_ecs_task_definition.jenkins_controller.arn
  cluster          = data.terraform_remote_state.remote_state_ecs.outputs.ecs_cluster_id
  desired_count    = 1
  launch_type      = "FARGATE"
  platform_version = "1.4.0"

  // Assuming we cannot have more than one instance at a time. Ever.
  deployment_maximum_percent         = 100
  deployment_minimum_healthy_percent = 0


  service_registries {
    registry_arn = aws_service_discovery_service.controller.arn
   }

  load_balancer {
    target_group_arn = data.terraform_remote_state.remote_state_alb.outputs.tg_arn
    container_name   = "${var.prefix}-${var.appName}"
    container_port   = 8080
  }

  network_configuration {
    subnets          = flatten([module.vpc_presets.subnet_ids])

    security_groups  = data.terraform_remote_state.remote_state_sg.outputs.ecs_sg
    assign_public_ip = false
  }
  tags           = var.tags
}

ANSWER

Answered 2021-Jun-09 at 15:01

I had a related problem because the directory has not yet been created, there is a property in root_directory that allows creating the directory with proper permissions.

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/efs_access_point#creation_info

In the example I use root, but you can set another gid.

resource "aws_efs_access_point" this  {
  file_system_id = aws_efs_file_system.efs.id
  root_directory {
    path = "/desired-directory"
    creation_info {
      owner_gid = 0
      owner_uid = 0
      permissions = "755"
    }
  }
}

Source https://stackoverflow.com/questions/67901275

QUESTION

Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set from Kafka rest proxy

Asked 2021-Jun-13 at 10:23

I am trying to use kafka rest proxy for AWS MSK cluster.

MSK Encryption details:

Within the cluster

TLS encryption: Enabled

Between clients and brokers

TLS encryption: Enabled

Plaintext: Not enabled

I have created topic "TestTopic" on MSK and then I have created another EC2 instance in the same VPC as MSK to work as Rest proxy. Here are details from kafka-rest.properties:

zookeeper.connect=z-3.msk.xxxx.xx.xxxxxx-1.amazonaws.com:2181,z-1.msk.xxxx.xx.xxxxxx-1.amazonaws.com:2181
bootstrap.servers=b-1.msk.xxxx.xx.xxxxxx-1.amazonaws.com:9096,b-2.msk.xxxx.xx.xxxxxx-1.amazonaws.com:9096
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="username" password="password";
security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-512
ssl.truststore.location=/tmp/kafka.client.truststore.jks

I have also created rest-jaas.properties file with below content:

KafkaClient {
  org.apache.kafka.common.security.scram.ScramLoginModule required
  username="username"
  password="password";
};

and then set the java.security.auth.login.config using:

export KAFKA_OPTS=-Djava.security.auth.login.config=/home/ec2-user/confluent-6.1.1/rest-jaas.properties

After this I started Kafka rest proxy using:

./kafka-rest-start /home/ec2-user/confluent-6.1.1/etc/kafka-rest/kafka-rest.properties

But when I tried to put an event on the TestTopic by calling service from postman: POST: http://IP_of_ec2instance:8082/topics/TestTopic I am getting 500 error. But in the EC2 instance I can see error:

Caused by: org.apache.kafka.common.KafkaException: Failed to construct kafka producer
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:441)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:291)
    at io.confluent.kafkarest.ProducerPool.buildNoSchemaProducer(ProducerPool.java:120)
    at io.confluent.kafkarest.ProducerPool.buildBinaryProducer(ProducerPool.java:106)
    at io.confluent.kafkarest.ProducerPool.<init>(ProducerPool.java:71)
    at io.confluent.kafkarest.ProducerPool.<init>(ProducerPool.java:60)
    at io.confluent.kafkarest.ProducerPool.<init>(ProducerPool.java:53)
    at io.confluent.kafkarest.DefaultKafkaRestContext.getProducerPool(DefaultKafkaRestContext.java:54)
    ... 64 more
Caused by: java.lang.IllegalArgumentException: Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set
    at org.apache.kafka.common.security.JaasContext.defaultContext(JaasContext.java:141)
    at org.apache.kafka.common.security.JaasContext.load(JaasContext.java:106)
    at org.apache.kafka.common.security.JaasContext.loadClientContext(JaasContext.java:92)
    at org.apache.kafka.common.network.ChannelBuilders.create(ChannelBuilders.java:139)
    at org.apache.kafka.common.network.ChannelBuilders.clientChannelBuilder(ChannelBuilders.java:74)
    at org.apache.kafka.clients.ClientUtils.createChannelBuilder(ClientUtils.java:120)
    at org.apache.kafka.clients.producer.KafkaProducer.newSender(KafkaProducer.java:449)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:430)
    ... 71 more

I can also see that value of sasl.jaas.config = null in the ProducerConfig values.

Could someone please help me with this. Thanks in advance!

ANSWER

Answered 2021-Jun-13 at 10:23

Finally the issue was fixed. I am updating the fix here so that it can be beneficial for someone:

kafka-rest.properties file should have below text:

zookeeper.connect=z-3.msk.xxxx.xx.xxxxxx-1.amazonaws.com:2181,z-1.msk.xxxx.xx.xxxxxx-1.amazonaws.com:2181
bootstrap.servers=b-1.msk.xxxx.xx.xxxxxx-1.amazonaws.com:9096,b-2.msk.xxxx.xx.xxxxxx-1.amazonaws.com:9096
client.sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="username" password="username";
client.security.protocol=SASL_SSL
client.sasl.mechanism=SCRAM-SHA-512

Neither there was a need to create file rest-jaas.properties nor export KAFKA_OPTS was needed.

After these changes, I was able to put the messages in the kafka topic using scram authentication.

Source https://stackoverflow.com/questions/67869549

QUESTION

Oracle SQL Encryption Using a Cell Value Password

Asked 2021-Jun-13 at 08:07

I am new to Oracle SQL,

And have following requirement,

There is a customer table with following columns,

customer (customer_id, customer_name, contact_number, credit_card_number, income, password)

Credit card number and the income are to be encrypted by the given password which is in the password column.

Is there any way to do this ? I have done a extensive internet search and could not find a answer.

Thanks in advance.

Edit 2: My encrypt_decrypt package for password column encryption

CREATE OR REPLACE PACKAGE field_encrypt_decrypt
AS
   FUNCTION encrypt (p_plainText VARCHAR2) RETURN RAW DETERMINISTIC;
   FUNCTION decrypt (p_encryptedText RAW) RETURN VARCHAR2 DETERMINISTIC;
END;

CREATE OR REPLACE PACKAGE BODY encrypt_decrypt
AS
     encryption_type    PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                                     + DBMS_CRYPTO.CHAIN_ECB
                                     + DBMS_CRYPTO.PAD_PKCS5;

     encryption_key     RAW (32) := UTL_RAW.cast_to_raw('01234567890123450123456789012345');

     -- The encryption key for DES algorithm, should be 8 bytes or more.

    
   /* Input plaintext to encrypt with the given key in the package */

     FUNCTION encrypt (p_plainText VARCHAR2) RETURN RAW DETERMINISTIC
     IS
        encrypted_raw      RAW (2000);

    /* The encryption or decryption on VARCHAR2 doesn't work directly using   DBMS_CRYPTO, therefore, convert input to RAW before encrypting it */

     BEGIN
        encrypted_raw := DBMS_CRYPTO.ENCRYPT
        (
           src => UTL_RAW.CAST_TO_RAW (p_plainText),
           typ => encryption_type,
           key => encryption_key
        );
       RETURN encrypted_raw;
     END encrypt;


     FUNCTION decrypt (p_encryptedText RAW) RETURN VARCHAR2 DETERMINISTIC
     IS
        decrypted_raw      RAW (2000);
     BEGIN
        decrypted_raw := DBMS_CRYPTO.DECRYPT
        (
            src => p_encryptedText,
            typ => encryption_type,
            key => encryption_key
        );
        RETURN (UTL_RAW.CAST_TO_VARCHAR2 (decrypted_raw));
     END decrypt;
END;

ANSWER

Answered 2021-Jun-13 at 08:07

Manage to do the task, Craeting Package therdata_encrypt_decrypt

CREATE OR REPLACE PACKAGE otherdata_encrypt_decrypt
AS
   FUNCTION encrypt (p_plainText VARCHAR2,p_password VARCHAR2) RETURN RAW DETERMINISTIC;
   FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC;
END;
/

CREATE OR REPLACE PACKAGE BODY otherdata_encrypt_decrypt
AS
     encryption_type    PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                                     + DBMS_CRYPTO.CHAIN_ECB
                                     + DBMS_CRYPTO.PAD_PKCS5;

   /* Input plaintext to encrypt with the given key in the package */
    
     
     FUNCTION encrypt (p_plainText VARCHAR2, p_password VARCHAR2) RETURN RAW DETERMINISTIC
     IS
        encrypted_raw      RAW (2000);

    /* The encryption or decryption on VARCHAR2 doesn't work directly using   DBMS_CRYPTO, therefore, convert input to RAW before encrypting it */

     BEGIN
        encrypted_raw := DBMS_CRYPTO.ENCRYPT
        
        (
           src => UTL_RAW.CAST_TO_RAW (p_plainText),
           typ => encryption_type,
           /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
           key => UTL_RAW.cast_to_raw(LPAD(p_password,32,'A'))
        );
       RETURN encrypted_raw;
     END encrypt;


     FUNCTION decrypt (p_encryptedText RAW,p_password VARCHAR2) RETURN VARCHAR2 DETERMINISTIC
     IS
        decrypted_raw      RAW (2000);
     BEGIN
        decrypted_raw := DBMS_CRYPTO.DECRYPT
        
        (
            src => p_encryptedText,
            typ => encryption_type,
            /* Key Length Needs to be 32 for AES 256 Encryption Since Padding with A */
            key => UTL_RAW.cast_to_raw (LPAD(p_password,32,'A'))
        );
        RETURN (UTL_RAW.CAST_TO_VARCHAR2 (decrypted_raw));
     END decrypt;
END;

Creating a Procedure

create or replace PROCEDURE CUSTOMERDEPT.insert_encrypt
(p_customer_id in customer.customer_id%TYPE,
p_customer_name in customer.customer_name%TYPE,
p_contact_number in customer.contact_number%TYPE,
p_credit_card_number in customer.credit_card_number%TYPE,
p_income in customer.income%TYPE,
p_password in customer.password%TYPE)
    IS
    
        encrypt_credit_card_no RAW(200);
        encrypt_income RAW(200);
        p_password_encrypt RAW(200);
        
        BEGIN
            
            encrypt_credit_card_no:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_credit_card_number,p_password);
            encrypt_income:=SYS.OTHERDATA_ENCRYPT_DECRYPT.ENCRYPT(p_income,p_password);
            p_password_encrypt:=SYS.ENCRYPT_DECRYPT.ENCRYPT(p_password);
        
            INSERT INTO customer(customer_id, customer_name, contact_number, credit_card_number, income, password)
            VALUES (p_customer_id,p_customer_name,p_contact_number,encrypt_credit_card_no,encrypt_income,p_password_encrypt);
            COMMIT;
    END;

Testing:

EXEC insert_encrypt (7, Test123, 0777712345, '11112223334455', '2222.22', '122122')

Source https://stackoverflow.com/questions/67906297

QUESTION

How to encrypt any file no matter what type it is with Python?

Asked 2021-Jun-12 at 08:03

So I tried to read the file and encrypt its content with cryptography.fernet but sometimes the file contains characters that can't be encrypted by whatever algorithm is being used in this library. I also tried a library called pyAesCrypt which has this function: pyAesCrypt.encryptFile("data.txt", "data.txt.aes", password). But it also can't encrypt some file types like gifs. I don't know much about the encryption algorithm happening in the background, but is there any way I can encrypt all files no matter what characters they contain? Or maybe encode them first to get rid of these characters then encrypt them? I'm just giving ideas based on the small knowledge I have about this topic.

The code I tried with Fernet library:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)

with open(filename, "r") as file:
    file_data = file.read()
    encrypted_data = f.encrypt(file_data.encode()).decode()

with open(filename, "w") as file:
    file.write(encrypted_data)

When I try this with GIFs I get:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 466: character maps to <undefined>

ANSWER

Answered 2021-Jun-12 at 08:03

you must open file in binary mode for reading and writing. since encrypt method expect bytes as a parameter, this way you can encrypt any file no matter it's type.

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)

with open(filename, "rb") as file:
    file_data = file.read()
    encrypted_data = f.encrypt(file_data)

with open(filename, "wb") as file:
    file.write(encrypted_data)

Source https://stackoverflow.com/questions/67944504

QUESTION

PGPy throwing error when using BCPG public key

Asked 2021-Jun-11 at 17:35

I'm new to PGP encryption and I'm trying to understand a problem I'm having. I have this public key (taken from some examples online)

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: BCPG v1.58

mI0EWiOMeQEEAImCEQUnSQ54ee+mnkANsjyvZm2QsC1sGIBEpmyJbh2xWuluJ/KV
TIUSqbkLOEq4COIlzG0fhuruUWBM2+ANazq5jkxLrYmHX4AwA2Q6jvd3xE8B1uVj
qT0TEKyZtmBwesEswUxb+vOwVLdWKXpcySXtIQhoKWAUVzG7e5uEawyXABEBAAG0
BWFuaXNoiJwEEAECAAYFAlojjHkACgkQmCS94uDDx9lHewP/UtsSk3lyj5GnHyoT
HZMz+sUFpFlan7agqHf6pV2Pgdb9OMCVauMwl9bjPY9HSHQg/a3gTQ5qNq9txiI2
4Fso2Q3AR6XcVk2wQxS6prJ9imPi1npXarCwZkEgWLXWLuQLHoxRWHf9olUqeW7P
kwQlJ1K9Ib85pCTvx16DN7QwQv8=
=Qteg
-----END PGP PUBLIC KEY BLOCK-----

With this code:

pub_key = pgpy.PGPKey()
pub_key.parse(KEY_PUB)

SOME_TEXT = 'Hello, world'

msg = pgpy.PGPMessage.new(SOME_TEXT)

encrypted_message = pub_key.encrypt(msg)

pgpstr = str(encrypted_message)

print(pgpstr)

I get this error:

pgpy.errors.PGPError: Key 9824BDE2E0C3C7D9 does not have the required usage flag EncryptStorage, EncryptCommunications

But everything works if I use this other key:

-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: Alice's OpenPGP certificate
Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html

mDMEXEcE6RYJKwYBBAHaRw8BAQdArjWwk3FAqyiFbFBKT4TzXcVBqPTB3gmzlC/U
b7O1u120JkFsaWNlIExvdmVsYWNlIDxhbGljZUBvcGVucGdwLmV4YW1wbGU+iJAE
ExYIADgCGwMFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AWIQTrhbtfozp14V6UTmPy
MVUMT0fjjgUCXaWfOgAKCRDyMVUMT0fjjukrAPoDnHBSogOmsHOsd9qGsiZpgRnO
dypvbm+QtXZqth9rvwD9HcDC0tC+PHAsO7OTh1S1TC9RiJsvawAfCPaQZoed8gK4
OARcRwTpEgorBgEEAZdVAQUBAQdAQv8GIa2rSTzgqbXCpDDYMiKRVitCsy203x3s
E9+eviIDAQgHiHgEGBYIACAWIQTrhbtfozp14V6UTmPyMVUMT0fjjgUCXEcE6QIb
DAAKCRDyMVUMT0fjjlnQAQDFHUs6TIcxrNTtEZFjUFm1M0PJ1Dng/cDW4xN80fsn
0QEA22Kr7VkCjeAEC08VSTeV+QFsmz55/lntWkwYWhmvOgE=
=iIGO
-----END PGP PUBLIC KEY BLOCK-----

So I would like to understand what is the difference between the 2 keys and how can I make the first one work. Thank you in advance!

ANSWER

Answered 2021-Jun-11 at 17:35

The error message explicitly tells you that the key that fails doesn't describe itself as suitable for encrypted storage or communications.

Per the signature subpacket specification, we know that this information lives in a subpacket of type 27.

Per the detailed specification on that subpacket, we know that the desired flags are 0x04 and 0x08, respectively.


To compare these keys, you can use gpg --list-packets --verbose.

For the first, non-working key, we get:

gpg: armor header: Version: BCPG v1.58
# off=0 ctb=98 tag=6 hlen=2 plen=141
:public key packet:
        version 4, algo 1, created 1512279161, expires 0
        pkey[0]: 8982110527490E7879EFA69E400DB23CAF666D90B02D6C188044A66C896E1DB15AE96E27F2954C8512A9B90B384AB808E225CC6D1F86EAEE51604CDBE00D6B3AB98E4C4BAD89875F803003643A8EF777C44F01D6E563A93D1310AC99B660707AC12CC14C5BFAF3B054B756297A5CC925ED2108682960145731BB7B9B846B0C97
        pkey[1]: 010001
        keyid: 9824BDE2E0C3C7D9
# off=143 ctb=b4 tag=13 hlen=2 plen=5
:user ID packet: "anish"
# off=150 ctb=88 tag=2 hlen=2 plen=156
:signature packet: algo 1, keyid 9824BDE2E0C3C7D9
        version 4, created 1512279161, md5len 0, sigclass 0x10
        digest algo 2, begin of digest 47 7b
        hashed subpkt 2 len 4 (sig created 2017-12-03)
        subpkt 16 len 8 (issuer key ID 9824BDE2E0C3C7D9)
        data: 52DB129379728F91A71F2A131D9333FAC505A4595A9FB6A0A877FAA55D8F81D6FD38C0956AE33097D6E33D8F47487420FDADE04D0E6A36AF6DC62236E05B28D90DC047A5DC564DB04314BAA6B27D8A63E2D67A576AB0B066412058B5D62EE40B1E8C515877FDA2552A796ECF9304252752BD21BF39A424EFC75E8337B43042FF

This key contains no signature subpackets of type 27 at all.


For the second, working key, we get:

gpg: armor header: Comment: Alice's OpenPGP certificate
gpg: armor header: Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html
# off=0 ctb=98 tag=6 hlen=2 plen=51
:public key packet:
        version 4, algo 22, created 1548158185, expires 0
        pkey[0]: 092B06010401DA470F01 ed25519 (1.3.6.1.4.1.11591.15.1)
        pkey[1]: 40AE35B0937140AB28856C504A4F84F35DC541A8F4C1DE09B3942FD46FB3B5BB5D
        keyid: F231550C4F47E38E
# off=53 ctb=b4 tag=13 hlen=2 plen=38
:user ID packet: "Alice Lovelace <alice@openpgp.example>"
# off=93 ctb=88 tag=2 hlen=2 plen=144
:signature packet: algo 22, keyid F231550C4F47E38E
        version 4, created 1571135290, md5len 0, sigclass 0x13
        digest algo 8, begin of digest e9 2b
        hashed subpkt 27 len 1 (key flags: 03)
        hashed subpkt 11 len 4 (pref-sym-algos: 9 8 7 2)
        hashed subpkt 21 len 5 (pref-hash-algos: 10 9 8 11 2)
        hashed subpkt 22 len 3 (pref-zip-algos: 2 3 1)
        hashed subpkt 30 len 1 (features: 01)
        hashed subpkt 23 len 1 (keyserver preferences: 80)
        hashed subpkt 33 len 21 (issuer fpr v4 EB85BB5FA33A75E15E944E63F231550C4F47E38E)
        hashed subpkt 2 len 4 (sig created 2019-10-15)
        subpkt 16 len 8 (issuer key ID F231550C4F47E38E)
        data: 039C7052A203A6B073AC77DA86B226698119CE772A6F6E6F90B5766AB61F6BBF
        data: 1DC0C2D2D0BE3C702C3BB3938754B54C2F51889B2F6B001F08F69066879DF202
# off=239 ctb=b8 tag=14 hlen=2 plen=56
:public sub key packet:
        version 4, algo 18, created 1548158185, expires 0
        pkey[0]: 0A2B060104019755010501 cv25519 (1.3.6.1.4.1.3029.1.5.1)
        pkey[1]: 4042FF0621ADAB493CE0A9B5C2A430D8322291562B42B32DB4DF1DEC13DF9EBE22
        pkey[2]: 03010807
        keyid: 4766F6B9D5F21EB6
# off=297 ctb=88 tag=2 hlen=2 plen=120
:signature packet: algo 22, keyid F231550C4F47E38E
        version 4, created 1548158185, md5len 0, sigclass 0x18
        digest algo 8, begin of digest 59 d0
        hashed subpkt 33 len 21 (issuer fpr v4 EB85BB5FA33A75E15E944E63F231550C4F47E38E)
        hashed subpkt 2 len 4 (sig created 2019-01-22)
        hashed subpkt 27 len 1 (key flags: 0C)
        subpkt 16 len 8 (issuer key ID F231550C4F47E38E)
        data: C51D4B3A4C8731ACD4ED1191635059B53343C9D439E0FDC0D6E3137CD1FB27D1
        data: DB62ABED59028DE0040B4F15493795F9016C9B3E79FE59ED5A4C185A19AF3A01

Here, the main key is configured only for signing data and certifying other keys (value is 3 == 2 (signing data) + 1 (certifying other keys)); but it has subkey with a flag of 0x0C, aka decimal 12, aka 8 (encrypting data) + 4 (encrypting storage).


Finally, inside PGPy, the encrypt method has a decorator @KeyAction(KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage, is_public=True), which actually validates the flags in question.

It is conceivable that the if len(self.flags) clause therein is intended to skip this check for keys that don't have any subpacket listing usage flags at all. If this is the case, it is conceivable that the above would be accepted as a bug report, insofar as this code is performing usage checks against a key with no usage data present.

Source https://stackoverflow.com/questions/67911087

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

VULNERABILITIES

No vulnerabilities reported

INSTALL Encryption

You can use Encryption like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the Encryption component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

SUPPORT

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

Implement Encryption faster with kandi.

  • Use the support, quality, security, license, reuse scores and reviewed functions to confirm the fit for your project.
  • Use the, Q & A, Installation and Support guides to implement faster.

Discover Millions of Libraries and
Pre-built Use Cases on kandi