Initial 16 characters of the deciphered message are nonsensical

In a specific scenario, I encounter data encryption from the API followed by decryption in TypeScript. I have utilized CryptoJS for decryption in TypeScript. Below is the decryption code snippet:

decrypt(source: string, iv: string): string {
var key = environment.config.KEY_PAYMENT.substring(0, 32);
const keyValue = CryptoJS.enc.Utf8.parse(key);
const ivValue = CryptoJS.enc.Utf8.parse(iv);
const plainText = CryptoJS.AES.decrypt(source, keyValue, {
  keySize: 16,
  iv: ivValue,
  mode: CryptoJS.mode.CBC,
  padding: CryptoJS.pad.Pkcs7
});
return CryptoJS.enc.Latin1.stringify(plainText);

} The provided IV and key values are crucial. Additionally, I have a Java code sample used for decryption on a mobile application that is functioning as intended. The code sample is as follows:

fun decrypt(
    source: ByteArray,
    key: String,
    iv: ByteArray
  ): ByteArray {
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, makeKey(key), makeIv(iv))
    return cipher.doFinal(source)
  }

  private fun makeIv(iv: ByteArray): AlgorithmParameterSpec {
    return IvParameterSpec(iv)
  }

  private fun makeKey(baseKey: String): Key? {
    return try {
      val key = baseKey.substring(0, 32)
          .toByteArray(charset("UTF-8"))
      SecretKeySpec(key, "AES")
    } catch (e: UnsupportedEncodingException) {
      null
    }
  }

Sample Output:

ªîto7“ßH«3©@V¨sr","paymentType":"credit_card",...

Upon decryption, the first 16 characters appear as garbage while the remaining string is successfully decrypted. Assistance is needed at this point.

Answer №1

"If the first 16 characters are incorrect but everything else appears correct", it often indicates an issue with the IV.

Upon reviewing the code you shared, it seems to be in order. My suspicion lies with the decrypt function not receiving the accurate IV value from the caller.

Answer №2

Here is the solution that worked for me:

  decipher(input: string, initializationVector: string) {
    debugger;
    var secretKey = environment.config.SECRET_KEY.slice(0, 32);
    const keyVal = CryptoJS.enc.Utf8.parse(secretKey);
    const ivValue = CryptoJS.enc.Base64.parse(initializationVector);//This Line
    const decryptedText = CryptoJS.AES.decrypt(input, keyVal, { iv: ivValue });
    return CryptoJS.enc.Latin1.stringify(decryptedText);
  }

I found that CryptoJS has its own built-in base64 encoding function, which gave me the correct output.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

What methods are most effective for verifying user credentials in a web application using Node.js and AngularJS?

Currently, I am working on a project that involves using Node.js and MySQL for handling user data. I would like to leverage the user information stored in the MySQL database, but I am unsure about the most secure method for implementing user authentication ...

Removing an item from a table row cannot be completed due to the inability to retrieve the list_body ID necessary for deletion

I have been working on enhancing the delete button function in my table. The id linked to the list_body must be incorporated into the delete function code. I utilized some jquery methods to render the list onto the webpage. //retrieve user list information ...

Looking to reset the default display option in a select dropdown using JavaScript or jQuery?

Here is some HTML code for a select element: <select> <br> <option>1</option><br> <option>2</option><br> </select> This select element will initially display the first option item (display ...

Inconsistencies in spacing between shapes bordering an SVG Circle using D3.js are not consistent across platforms

After creating a SVG circle and surrounding it with rectangles, I am now attempting to draw a group of 2 rectangles. The alignment of the rectangle combo can either be center-facing or outside-facing, depending on the height of the rectangle. However, I am ...

Converting the following ngRx selector to a boolean return – a guide

I am currently using the following filter to retrieve a list of data within a specific date range. I have implemented logic in the component where I check the length of the list and assign True or False to a variable based on that. I am wondering if ther ...

What are some of the techniques for customizing the DOM generated by material-ui in ReactJS?

Is there a way to style the dynamically created DOM elements from material-ui? I'm currently using GridListTileBar, which generates a DOM structure like this for its title property. <div class="MuiGridListTileBar-title-29" data-reactid=".0.3.0.$3 ...

Transforming a string into JSON with proper sanitization

When web scraping, the website returns a string like this on get request: jQuery18305426675335038453_1429531451051({"d":[{"__metadata":"cool"}]}) The complete code snippet is provided below: var baseUrl = "http://SOMEURL.COM?spatialFilter=nearby(52.4795 ...

Uncovering the Mystery of Undefined Dom Ref Values in Vue 3 Templaterefs

I am currently experimenting with the beta version of Vue 3 and encountering an issue while trying to access a ref in the setup function. Here is my component: JS(Vue): const Child = createComponent({ setup () { let tabs = ref() console.log(t ...

Retrieving all the information stored in the tables

I'm struggling with retrieving the content of my table cells. Some cells contain a hyphen (-) and if they do, I want to center the text. I'm facing difficulties with my jQuery code, particularly the if statement which always evaluates to false. ...

AngularJS: enhancing $http with custom functionality

I am facing an issue with my simple controller, which looks like this: function MyController($scope, $http) { ... $http.post(url).success(function(data) { console.log(data) }); } MyController.$inject = ['$scope', &ap ...

stuck with an outdated dependency causing issues with create-react-app

Encountering a problem with create-react-app failing due to react-scripts expecting an older version of a dependency, making it difficult to select the new version as suggested. This appears to be an interface issue. Interestingly, I can successfully inst ...

Performing a function when text is clicked: Utilizing AngularJS

My goal is to trigger a specific controller method upon clicking on certain text. This function will then make remote calls to another server and handle the display of another div based on the response. Additionally, I need to pass parameters to this funct ...

Ways in which this data can be best retrieved

Hey there, I'm currently in the process of building an Ionic2 app with Firebase integration. Within my codebase, there's a provider known as Students-services where I've written a function to navigate through a node, retrieve values, and dis ...

Display HTML content within a Material-UI Card component using React

Currently, I am utilizing the < CardHeader /> component nested within a < Card />. <CardHeader title={card.title} subheader={`${moment(card.createdAt).startOf('minute').fromNow()}` + ' by ' + <div>ABC</div>}/ ...

how can I pass a group of values as an argument in math.sum function?

Using math.js for convenience, I was intrigued if I could utilize the math.sum method to calculate the sum of a collection of input values. For example, something along the lines of: Here's a snippet of code to help visualize my concept: $(documen ...

Can a string or javascript object be uploaded without being saved in a file? - IPFS

I've been exploring the capabilities of js-ipfs API and I'm curious to know if js-ipfs is limited to only uploading files/folders. Is there a way to upload other types of data, such as a JavaScript object like: { heading:"SomeHeading", c ...

Accessing the SQL database using Cypress

I am attempting to establish a connection with an SQL database using Cypress following the guidelines provided in the NPM guide. I have ensured that all dependencies are installed as specified, however, when I run the following query: cy.sqlServer('S ...

ways to assign the total of string array elements to the $scope variable

I've been working on binding the total sum of selected checkboxes within a table. I'm almost there, but something isn't quite right. The image above shows 2 checkboxes selected. https://i.sstatic.net/70af2.jpg The code snippet below showcas ...

Synchronize custom directive controller data with data from a factory

As a newcomer to angularjs, I stumbled upon this example that I found somewhere and it works perfectly well. However, I am puzzled by how the data within the customized directive controller remains synchronized with the factory data. Here is the snippet of ...