Encrypt with AES in TypeScript and decrypt in Go programming language

Looking for assistance with encrypting data in TypeScript and then decrypting it in Go. The issue I'm facing is that the output in Go does not match the input in TypeScript. What could be causing this discrepancy?

Below is my TypeScript code:

import * as CryptoJS from 'crypto-js';
var key = CryptoJS.enc.Utf8.parse('7061737323313233');
var iv = CryptoJS.enc.Utf8.parse('7061737323313233');
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse("Im new in aes encryption"), key,
    {
        keySize: 128 / 8,
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
    keySize: 128 / 8,
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
});

console.log('Encrypted :' + encrypted);
console.log('Key :' + encrypted.key);
console.log('Salt :' + encrypted.salt);
console.log('iv :' + encrypted.iv);
console.log('Decrypted : ' + decrypted);
console.log('utf8 = ' + decrypted.toString(CryptoJS.enc.Utf8));

And here is my Go code:

func main() {
    d2, _ := Decrypt("VMlk9qzp2BKZi5wZjlzst2iwEre0uD/VHVc6xm2bhXY=", "37303631373337333233333133323333")
    fmt.Println(d2)
}
// Decrypt-function to decrypt the given cipher text string into plain text string
func Decrypt(encrypted string, CIPHER_KEY string) (string, error) {
    key := []byte(CIPHER_KEY)
    cipherText, _ := base64.StdEncoding.DecodeString(encrypted) ////hex.DecodeString(encrypted)

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    if len(cipherText)<aes.BlockSize {
        panic("cipherText too short")
    }
    iv := cipherText[:aes.BlockSize]

    cipherText = cipherText[aes.BlockSize:]
    if len(cipherText)%aes.BlockSize!=0 {
        panic("cipherText is not a multiple of the block size")
    }
    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(cipherText, cipherText)

    cipherText, _ = pkcs7.Pad(cipherText, aes.BlockSize)
    return fmt.Sprintf("%s", cipherText), nil
}

Answer №1

  1. Make sure to utilize the key "7061737323313233".
  2. Keep the initialization vector the same.
  3. Decrypt the entire text.
func main() {

    decryptedText, err := Decrypt("VMlk9qzp2BKZi5wZjlzst2iwEre0uD/VHVc6xm2bhXY=", "7061737323313233")
    if err != nil {
        log.Println(err)
        return
    }
    fmt.Println(decryptedText)

}

// Decrypt function decrypts an encrypted cipher text string into plain text string
func Decrypt(encryptedString string, CIPHER_KEY string) (string, error) {
    key := []byte(CIPHER_KEY)
    cipherText, _ := base64.StdEncoding.DecodeString(encryptedString) ////hex.DecodeString(encryptedString)

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    if len(cipherText) < aes.BlockSize {
        panic("cipherText too short")
    }
    
    iv := []byte("7061737323313233")

    cipherText = cipherText[:]
    if len(cipherText)%aes.BlockSize != 0 {
        panic("cipherText is not a multiple of the block size")
    }

    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(cipherText, cipherText)

    return fmt.Sprintf("%s", cipherText), nil
}

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

Issue with the close button on ngb-alert not functioning properly

As I develop my website, I have incorporated an ngb-alert component to display an alert message to users upon login. While the alert itself is functioning properly, I have encountered an issue with the close button being misaligned, and I am struggling to ...

Try utilizing toMatchObject along with stringMatching(regexp) in your Jest tests

When using the JEST matcher toMatchObject, my objective is to ensure that an object contains certain properties with static values, while other values should match specific regular expressions. The issue I'm facing is that when a static value doesn&a ...

Setting the default value for a useRef<HTMLInputElement> in ReactJs with Typescript

Is there a way to assign a number as the initial value on useRef<HTMLInputElement> without using useState<number>() since the field is a simple counter? Below is my TypeScript code: const MyComponent = () => { const productAmountRef = us ...

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

How to deduce a string literal using a ternary conditional in TypeScript

Here is a simple illustration: function doSomething(animal: 'bird' | 'fish'){ } let flies=true; const animal = flies ? 'bird' : 'fish' doSomething(animal); In the assignment to `animal` from the ternary conditio ...

Troubleshooting: Unable to filter reducers in Redux when using the remove

I'm attempting to eliminate an element from an array using the filter method in this manner: removeDisplate: (state, action: PayloadAction<string>) => { console.log(action.payload); state.map((item) => { console.log(item.name); } ...

The ReplaySubject is receiving an updated response, however, the View is displaying the same information

Having an issue with the ReplaySubject in my code. It seems that after updating an Array, the new values are not reflecting on the UI. I can only see the old values unless I reload the page. I have tried using ngZone but it didn't help. The code is d ...

Error: Visual Studio unable to locate Firebase node module

After running the command npm install firebase --save in the root of my project folder, a firebase folder was successfully added to my node_modules directory and the packages.json file was updated accordingly. In addition to using typescript, I have an ap ...

Discovering the power of chaining operators in RxJS 6 by encapsulating .map within

I am in the process of updating my Observable code from RXJS 5 to version 6. import { Injectable } from '@angular/core'; import { Observable } from 'rxjs' import { AppConfig } from '../config/app-config'; import { Xapi } from ...

I am looking for a way to convert the date format from "yyyy-MM-dd" to "dd-MM-yyyy" in NestJs

I need help with changing the date format from "yyyy-MM-dd" to "dd-MM-yyyy". Currently, my entity code looks like this: @IsOptional() @ApiProperty({ example: '1999-12-12', nullable: true }) @Column({ type: 'date', nullable: true } ...

Angular Karma encountered an error: TypeError - It is unable to read the property '_id' as it is undefined

Encountering an issue while testing with karma jasmine, the error message appears as... TypeError: Cannot read property '_id' of undefined This is the Component.ts file: import { Component, OnInit } from '@angular/core'; import { ApiSe ...

I encountered TS2345 error: The argument type X cannot be assigned to the parameter type Y

Currently, I am delving into the world of Angular 8 as a beginner with this framework. In my attempt to design a new user interface with additional elements, I encountered an unexpected linting error after smoothly adding the first two fields. The error m ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

Is it possible to utilize an enum for typing an array variable?

Is there a way to use an enum to define the valid types that an array can contain? I have been unable to find a solution so far, and I am curious if it is feasible. Below is the example code I have tried: interface User { name: string; } interface Ad ...

Angular routing prefix allows for defining a common prefix for

I currently have a range of components that utilize the router with absolute paths for navigation in certain scenarios. Let's take for example the EntityComponent, which has an action that navigates to /otherEntity/* URLs. This setup works perfectly ...

Strategies for modifying the bound value in Angular with an observable object

I am attempting to convert the offset value for a time object in the URI, which is stored in an observable object. The issue I am encountering is: ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checke ...

Look for identical values within a nested array

My data consists of a nested array where each element has a property called name, which can only be either A or B. I need to compare all elements and determine if they are all either A or B. Here is an example of the input: [ { "arr": { "teach ...

Excluding a common attribute from a combined type of objects can lead to issues when accessing non-common attributes (TypeScript)

In the process of developing a wrapper function, I am passing a refs property into a send function. The Event type used to construct my state machine is defined as an intersection between a base interface { refs: NodeRefs } and a union of possible event ob ...

"Angluar4 is throwing an error: it's unable to read the property 'iname' of

This is the code snippet from item.ts file:- export interface item{ $key?:string; available?:boolean; countable?:boolean; iname?:string; price?:string; desc?:string; image?:string; } The items component item.componenet.ts looks like this:- import { Com ...

What is the best way to verify that I am receiving the 'jwt' token in my code?

Trying to understand the data held by the jwt token in my next.js app, but encountering an error message saying error: jwt must be provided. Here's the code snippet causing the issue: import { NextRequest } from "next/server" ...