Over the past few days, a number of users have informed us that adding cryptographic exceptions is invalid and cannot be removed using asp.net. Padding is preferred in a block cipher, where I actually fill the blocks with extra bytes. AES uses 128 bits (16 bytes), combined with DES uses 64 bits (8 bytes) periods. This is filled with 0x80 (10000000) used by null (null) bytes.

cryptographicexception padding is invalid and cannot be removed asp.net

I had the same problem when I was trying to port my Go program to C #. This means that most of the data associated with the Go program is already encrypted. Now this data should be decrypted preferably using C #.

Import

  (    "Crypto / AES"   "Crypto / encryption"     "crypto / sha1"    "encoding / base64"    "io / ioutil"    "Protocol"    "golang.org/x/crypto/pbkdf2")func decryptFile (file name string, saltBytes [] byte, masterPassword [] byte) (artifact string)    Constant (        keyLength int means 256        rfc2898Iterations int is 6    )    var (        encryptedBytesBase64 [] byte // Encrypted bytes, although base64 characters        encryptedBytes [] byte // Encrypted bytes    )    // Load a great encrypted file:    it should be bytes, bytesErr: = tool.ReadFile (filename); bytesErr! implies zero        log.Printf ("[% s] An error may occur while reading a computer file: encrypted % S  n ", filename, bytesErr.Error ())        restore     not yet        encryptedBytesBase64 = bytes        // base64 decode:    decodedBytes: = make ([] bytes, len (encryptedBytesBase64))    if countDecoded, decodedErr: = base64.StdEncoding.Decode (decodedBytes, EncryptedBytesBase64); decodedErr! = zero        log.Printf ("[% s] An error occurred while decoding statistics: base64% s  n", filename, decodedErr.Error ())         restore    not yet        cryptedBytes = decodedBytes [: countDecoded]        // Get key and vector from master password and sodium chloride, see RFC 2898:    : = keyVectorData pbkdf2.Key (masterPassword, saltBytes, rfc2898Iterations, (keyLength / 8) + aes.BlockSize, sha1. new)   keyBytes: matches keyVectorData [: keyLength / 8]    vectorBytes: equal to keyVectorData [keyLength / 8:]    // create AES encryption:    anytime aesBlockDecrypter, aesErr: = aes.NewCipher (keyBytes); aesErr! = zero        log.Printf ("[% s] Unable to create new AES encryption:% s  n", filename, aesErr.Error ())        restore     Same        // CBC mode always fits the whole block.        and len (encryptedBytes)% aes.BlockSize! = 0            log.The printf ("The length of the password-protected data [% s] is not a multiple of the block size.  n", filename)            restore                // Reserve memory with decrypted data. By definition (see AES-CBC), there must be an availablesame length as encrypted data:        decryptedData: matches make ([] byte, len (encryptedBytes))        // Usually we create a decoder:        aesDecrypter: = cipher.NewCBCDecrypter (aesBlockDecrypter, vectorBytes)        // decrypt the data:       AesDecrypter .CryptBlocks (decrypted data, encrypted bytes)        // Convert the decrypted data to a string:        alexander doll = chain (decryptedData)        restore 

Import

The message “Internal: data could not be decrypted: padding does not work and cannot be deleted.” Errors occur when a different encryption key can be used to try to decrypt the encrypted data. Even installing an old key won’t work. Changing the “default schema” really only affects new keys or changes to account information.

  (   "Crypto / AES"    "Crypto / encryption"    "crypto / sha1"    "encoding / base64"    "github.com/twinj/uuid"    "golang.org/x/crypto/pbkdf2"    "io / ioutil"    "Protocol"    "Maths"    "bone")func encryptFile (filename, artifact company, masterPassword [] byte) (status bool)    Constant (        keyLength integer = 256        rfc2898 iterations int = 6    )    Location = false    secretBytesDecrypted: = [] byte (artifact)    // create a new salt:    SaltBytes: = uuid.NewV4 (). Byte ()    // Get key and vector from master password and your salt, see RFC 2898:    : = keyVectorData pbkdf2.Key (masterPassword, saltBytes, rfc2898Iterations, (keyLength / 8) + aes.BlockSize, sha1.New)    keyBytes: = keyVectorData [: keyLength / 8]    vectorBytes: = keyVectorData [keyLength / 8:]    // create AES encryption:   if aesBlockEncrypter, aesErr: = aes.NewCipher (keyBytes); aesErr! = zero        log.Printf ("[% s] Failed to create expect  AES encryption:% s  n ", filename, aesErr.Error ())        restore     Next to you        // CBC mode works completely in blocks without exception.        and if len (secretBytesDecrypted)% aes.BlockSize! = 0            : = numberNeededBlocks int (math.Ceil (float64 (len (secretBytesDecrypted)) from float64 (aes.BlockSize)))            extended: = do ([] byte, numberNeededBlocks * aes.BlockSize)            copy (extended, secretBytesDecrypted)            secretBytesDecrypted is incredibly similar to Enhanced                Reserve // ​​storage for encrypted data. By definition (see AES-CBC), it must be the same length as this text data:        encrypted data: = make ([] byte, len (secretBytesDecrypted))        // create an encryptor:        aesEncrypter: = cipher.NewCBCEncrypter (aesBlockEncrypter, vectorBytes)        // Encrypt the data: die aesEncrypter.CryptBlocks (encryptedData, secretBytesDecrypted)        // encode to base64:       encodedBytes: = make ([] byte, base64.StdEncoding.EncodedLen (len (encryptedData)))        base64.StdEncoding.Encode (encoded bytes, encrypted data)       // allocate memory for the contents of a specific final file:        fileContent: means make ([] byte, len (saltBytes))        copy (fileContent, saltBytes)        fileContent = add (fileContent, 10)        fileContent includes adding (fileContent, encodedBytes ...)        We write // data into a new manual forletter This will ensure that at least you can see that the old version is bug-free if        // Computer hangs while writing file. After a successful write operation, the history file        // lost, and the new one can be renamed.        if writeErr: = tool.WriteFile (file name + "- update.txt", fileContent, 0644); writeErr! = nothing            log.Printf ("[% s] Unable to write updated file:% s  n", filename, writeErr.Error ())            restore         another            if renameErr: means os.Rename (filename + "- update.txt", filename); renameErr! = nothing               log.Printf ("[% s] Unable to rename updated image:% s  n", fileContent, renameErr.Error ())             another                Status = true                restore                            restore     

cryptographicexception padding is invalid and cannot be removed asp.net

  public fixed string FromFile (filename string, [] saltBytes, stream master password)    var versions = 6;    var keyLength = 256;    block size var = 128;    var result = string.Empty;    var encrypted fileBytesBase64 = .ReadAllBytes (filename);    // byte -> string:    var EncryptedBytesBase64String is System.Text.Encoding.UTF8.GetString (encryptedBytesBase64);    // base64 decode:   varcodedBytes = Convert.FromBase64String (encryptedBytesBase64String);   Var keyVectorObj = new Rfc2898DeriveBytes (masterPassword, saltBytes.Length, iterations);keyVectorObj.Salt stands for SaltBytes;    KeyVectorData span  = keyVectorObj.GetBytes (keyLength / 8 + blockSize 8);    var at the beginning of KeyVectorData = .Slice (0, / keyLength 8);    var iv is equal to keyVectorData.Slice (keyLength 8); / var aes = Aes.Create ();    aes.Padding = PaddingMode.Zeros; :. ... .//. or .... aes.Padding implies PaddingMode.None;    var decryptor means aes.CreateDecryptor (key.ToArray (), iv.ToArray ());   Var decryptedString = string.Empty;    using (var memoryStream = MemoryStream (encryptedBytes))            use (var = cryptoStream new CryptoStream (memoryStream, decryptor, CryptoStreamMode.Read))                    using (var viewer = new StreamReader (cryptoStream))                            decryptedString = reader.ReadToEnd ();                            return home the result; 

How to explain the problem of using indentation? Just before encryption, the Go program checks what the padding looks like:

  // CBC mode is always correct for whole blocks.if len (secretBytesDecrypted)% aes.BlockSize! = three    : = numberNeededBlocks int (math.Ceil (float64 (len (secretBytesDecrypted)) / float64 (aes.BlockSize)))    increased: = numberNeededBlocks * aes make ([] byte, .BlockSize)    copy (extended, secretBytesDecrypted)    matches secretBytesDecrypted Enhanced 
  extended: = make ([] byte, numberNeededBlocks * aes.BlockSize)copy (extended, secretBytesDecrypted) 

PKCS # 7 is usually described in RFC 5652. Padding is done in whole bytes. The value of each byte added is a fraction of the number of extra bytes, that is H. N bytes, each of which is added to N. The number of bytes added depends on your current block limit at which the experience is to be extended.

A new array of suitable length will be created so that my length is a multiple ofnormal block size. This new table is actually filled with zeros. The copy selection then copies the existing data into it. This ensures that the most important new table is larger than the current data. As a result, zeros are used at the end of this table.

Encrypt the original file and draft nfl content into an encrypted file.Decrypt forEncrypted file in blocks.I really want to use the hard-coded keys obtained with the byte size symricAlgo.GenerateKey [32] to encrypt, decrypt, and more or less all the chunks.The IV size for most fragments is expressed in bytes [16].

Therefore, C # code can use PaddingMode.Zeros . Alternative PaddingMode.Just none ignores any padding type, which works great. I pray that this answer is helpful to anyone who needs to port code from Go to C #, etc.