Getting different result (cyphertext) while using AES in Java and golangDifferences between HashMap and Hashtable?Is Java “pass-by-reference” or “pass-by-value”?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?Creating a memory leak with JavaWhy is subtracting these two times (in 1927) giving a strange result?

Should I self-publish my novella on Amazon or try my luck getting publishers?

Japanese equivalent of a brain fart

Half-rock- half-forest-gnome

Why can I log in to my Facebook account with a misspelled email/password?

Is TEXT to VARCHAR(MAX) an implicit conversion?

Should I take out a personal loan to pay off credit card debt?

Why does putting a dot after the URL remove login information?

How to help new students accept function notation

Was there ever a difference between 'volo' and 'volo'?

Did silent film actors actually say their lines or did they simply improvise “dialogue” while being filmed?

Did WWII Japanese soldiers engage in cannibalism of their enemies?

What are these mathematical groups in U.S. universities?

How would I as a DM create a smart phone-like spell/device my players could use?

Why should public servants be apolitical?

What does VB stand for?

Validation and verification of mathematical models

Double blind peer review when paper cites author's GitHub repo for code

polynomial, find the sum of the inverse roots of this equation.

tikz-3dplot: angle-placed cones in a sphere

Short story about a teenager who has his brain replaced with a microchip (Psychological Horror)

Sets A such that A+A contains the largest set [0,1,..,t]

If there were no space agencies, could a person go to space?

Can I say "if a sequence is not bounded above, then it is divergent to positive infinity" without explicitly saying it's eventually increasing?

Does the United States guarantee any unique freedoms?



Getting different result (cyphertext) while using AES in Java and golang


Differences between HashMap and Hashtable?Is Java “pass-by-reference” or “pass-by-value”?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?Creating a memory leak with JavaWhy is subtracting these two times (in 1927) giving a strange result?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to replicate the java code for AES encryption into Golang.
However I am not getting the same output in golang



I tried below code:



Java Code:



package EncryptionTest;

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");
cipher = Cipher.getInstance("AES");
String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Java code output:
Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: vSmrgH3qU+qEq+3ui0YvwCa6PDBcMyhgOlbh3+zzM+cON6feLk2u1iPW7lITD3vn
Decrypted Text After Decryption: AES Symmetric Encryption Decryption



Golang Code:



package main

import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)

const NONCESIZE = 12

func main()
key := []byte("0123456789012345")
plaintext := []byte("AES Symmetric Encryption Decryption")
block, err := aes.NewCipher(key)
if err != nil
panic(err.Error())

nonce := make([]byte, NONCESIZE)
aesgcm, err := cipher.NewGCM(block)
if err != nil
panic(err.Error())

ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Println("Encrypted Text is : ", base64.StdEncoding.EncodeToString(ciphertext))




Golang Code output:
Encrypted Text is : 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp










share|improve this question
























  • Java's getBytes is not deterministic but depends on the default charset.

    – Volker
    Mar 27 at 6:13











  • AES use random initial vector for encryption. Every call generates random initial vector and this cause different encrypted text.

    – Dogushan KAYA
    Mar 27 at 7:18











  • @DogushanKAYA : The code which I pasted here, generating the same encrypted text.

    – Prashant Gupta
    Mar 27 at 8:57

















0















I am trying to replicate the java code for AES encryption into Golang.
However I am not getting the same output in golang



I tried below code:



Java Code:



package EncryptionTest;

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");
cipher = Cipher.getInstance("AES");
String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Java code output:
Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: vSmrgH3qU+qEq+3ui0YvwCa6PDBcMyhgOlbh3+zzM+cON6feLk2u1iPW7lITD3vn
Decrypted Text After Decryption: AES Symmetric Encryption Decryption



Golang Code:



package main

import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)

const NONCESIZE = 12

func main()
key := []byte("0123456789012345")
plaintext := []byte("AES Symmetric Encryption Decryption")
block, err := aes.NewCipher(key)
if err != nil
panic(err.Error())

nonce := make([]byte, NONCESIZE)
aesgcm, err := cipher.NewGCM(block)
if err != nil
panic(err.Error())

ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Println("Encrypted Text is : ", base64.StdEncoding.EncodeToString(ciphertext))




Golang Code output:
Encrypted Text is : 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp










share|improve this question
























  • Java's getBytes is not deterministic but depends on the default charset.

    – Volker
    Mar 27 at 6:13











  • AES use random initial vector for encryption. Every call generates random initial vector and this cause different encrypted text.

    – Dogushan KAYA
    Mar 27 at 7:18











  • @DogushanKAYA : The code which I pasted here, generating the same encrypted text.

    – Prashant Gupta
    Mar 27 at 8:57













0












0








0








I am trying to replicate the java code for AES encryption into Golang.
However I am not getting the same output in golang



I tried below code:



Java Code:



package EncryptionTest;

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");
cipher = Cipher.getInstance("AES");
String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Java code output:
Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: vSmrgH3qU+qEq+3ui0YvwCa6PDBcMyhgOlbh3+zzM+cON6feLk2u1iPW7lITD3vn
Decrypted Text After Decryption: AES Symmetric Encryption Decryption



Golang Code:



package main

import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)

const NONCESIZE = 12

func main()
key := []byte("0123456789012345")
plaintext := []byte("AES Symmetric Encryption Decryption")
block, err := aes.NewCipher(key)
if err != nil
panic(err.Error())

nonce := make([]byte, NONCESIZE)
aesgcm, err := cipher.NewGCM(block)
if err != nil
panic(err.Error())

ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Println("Encrypted Text is : ", base64.StdEncoding.EncodeToString(ciphertext))




Golang Code output:
Encrypted Text is : 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp










share|improve this question














I am trying to replicate the java code for AES encryption into Golang.
However I am not getting the same output in golang



I tried below code:



Java Code:



package EncryptionTest;

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");
cipher = Cipher.getInstance("AES");
String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Java code output:
Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: vSmrgH3qU+qEq+3ui0YvwCa6PDBcMyhgOlbh3+zzM+cON6feLk2u1iPW7lITD3vn
Decrypted Text After Decryption: AES Symmetric Encryption Decryption



Golang Code:



package main

import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)

const NONCESIZE = 12

func main()
key := []byte("0123456789012345")
plaintext := []byte("AES Symmetric Encryption Decryption")
block, err := aes.NewCipher(key)
if err != nil
panic(err.Error())

nonce := make([]byte, NONCESIZE)
aesgcm, err := cipher.NewGCM(block)
if err != nil
panic(err.Error())

ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Println("Encrypted Text is : ", base64.StdEncoding.EncodeToString(ciphertext))




Golang Code output:
Encrypted Text is : 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp







java go aes encryption-symmetric






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 5:59









Prashant GuptaPrashant Gupta

81 bronze badge




81 bronze badge















  • Java's getBytes is not deterministic but depends on the default charset.

    – Volker
    Mar 27 at 6:13











  • AES use random initial vector for encryption. Every call generates random initial vector and this cause different encrypted text.

    – Dogushan KAYA
    Mar 27 at 7:18











  • @DogushanKAYA : The code which I pasted here, generating the same encrypted text.

    – Prashant Gupta
    Mar 27 at 8:57

















  • Java's getBytes is not deterministic but depends on the default charset.

    – Volker
    Mar 27 at 6:13











  • AES use random initial vector for encryption. Every call generates random initial vector and this cause different encrypted text.

    – Dogushan KAYA
    Mar 27 at 7:18











  • @DogushanKAYA : The code which I pasted here, generating the same encrypted text.

    – Prashant Gupta
    Mar 27 at 8:57
















Java's getBytes is not deterministic but depends on the default charset.

– Volker
Mar 27 at 6:13





Java's getBytes is not deterministic but depends on the default charset.

– Volker
Mar 27 at 6:13













AES use random initial vector for encryption. Every call generates random initial vector and this cause different encrypted text.

– Dogushan KAYA
Mar 27 at 7:18





AES use random initial vector for encryption. Every call generates random initial vector and this cause different encrypted text.

– Dogushan KAYA
Mar 27 at 7:18













@DogushanKAYA : The code which I pasted here, generating the same encrypted text.

– Prashant Gupta
Mar 27 at 8:57





@DogushanKAYA : The code which I pasted here, generating the same encrypted text.

– Prashant Gupta
Mar 27 at 8:57












1 Answer
1






active

oldest

votes


















2














In the go code, you are using AES in GCM mode with 12 bytes of zero as IV, but in java code you are using default mode of AES which is not the same in different java versions.



By using GCM mode(Provided in BouncyCastle) and setting the same IV(12 bytes of zero) I got same output:



package EncryptionTest;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Key;
import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Security.addProvider(new BouncyCastleProvider());


Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");

cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");

String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();


byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);

byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Output:



Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp
Decrypted Text After Decryption: AES Symmetric Encryption Decryption





share|improve this answer

























  • Here I want to know what is the default mode which my java code is using and how to replicate the same in golang.

    – Prashant Gupta
    Mar 27 at 8:59











  • @PrashantGupta relying on default mode is risky. You should set it explicitly. As I said, you can use GCM in golang and java but if you don't want to use bouncy castle, you can use CBC mode in both languages.

    – Hamidreza Kalantari
    Mar 27 at 9:05










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55370699%2fgetting-different-result-cyphertext-while-using-aes-in-java-and-golang%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














In the go code, you are using AES in GCM mode with 12 bytes of zero as IV, but in java code you are using default mode of AES which is not the same in different java versions.



By using GCM mode(Provided in BouncyCastle) and setting the same IV(12 bytes of zero) I got same output:



package EncryptionTest;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Key;
import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Security.addProvider(new BouncyCastleProvider());


Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");

cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");

String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();


byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);

byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Output:



Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp
Decrypted Text After Decryption: AES Symmetric Encryption Decryption





share|improve this answer

























  • Here I want to know what is the default mode which my java code is using and how to replicate the same in golang.

    – Prashant Gupta
    Mar 27 at 8:59











  • @PrashantGupta relying on default mode is risky. You should set it explicitly. As I said, you can use GCM in golang and java but if you don't want to use bouncy castle, you can use CBC mode in both languages.

    – Hamidreza Kalantari
    Mar 27 at 9:05















2














In the go code, you are using AES in GCM mode with 12 bytes of zero as IV, but in java code you are using default mode of AES which is not the same in different java versions.



By using GCM mode(Provided in BouncyCastle) and setting the same IV(12 bytes of zero) I got same output:



package EncryptionTest;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Key;
import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Security.addProvider(new BouncyCastleProvider());


Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");

cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");

String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();


byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);

byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Output:



Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp
Decrypted Text After Decryption: AES Symmetric Encryption Decryption





share|improve this answer

























  • Here I want to know what is the default mode which my java code is using and how to replicate the same in golang.

    – Prashant Gupta
    Mar 27 at 8:59











  • @PrashantGupta relying on default mode is risky. You should set it explicitly. As I said, you can use GCM in golang and java but if you don't want to use bouncy castle, you can use CBC mode in both languages.

    – Hamidreza Kalantari
    Mar 27 at 9:05













2












2








2







In the go code, you are using AES in GCM mode with 12 bytes of zero as IV, but in java code you are using default mode of AES which is not the same in different java versions.



By using GCM mode(Provided in BouncyCastle) and setting the same IV(12 bytes of zero) I got same output:



package EncryptionTest;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Key;
import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Security.addProvider(new BouncyCastleProvider());


Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");

cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");

String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();


byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);

byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Output:



Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp
Decrypted Text After Decryption: AES Symmetric Encryption Decryption





share|improve this answer













In the go code, you are using AES in GCM mode with 12 bytes of zero as IV, but in java code you are using default mode of AES which is not the same in different java versions.



By using GCM mode(Provided in BouncyCastle) and setting the same IV(12 bytes of zero) I got same output:



package EncryptionTest;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Key;
import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionAES

static Cipher cipher;

public static void main(String[] args) throws Exception
Security.addProvider(new BouncyCastleProvider());


Key secretKey;
secretKey = (Key)new SecretKeySpec("0123456789012345".getBytes(), "AES");

cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");

String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);


public static String encrypt(String plainText, Key secretKey) throws Exception
byte[] plainTextByte = plainText.getBytes();


byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;


public static String decrypt(String encryptedText, Key secretKey) throws Exception
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);

byte[] iv = new byte[12];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;




Output:



Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp
Decrypted Text After Decryption: AES Symmetric Encryption Decryption






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 27 at 7:35









Hamidreza KalantariHamidreza Kalantari

4071 silver badge7 bronze badges




4071 silver badge7 bronze badges















  • Here I want to know what is the default mode which my java code is using and how to replicate the same in golang.

    – Prashant Gupta
    Mar 27 at 8:59











  • @PrashantGupta relying on default mode is risky. You should set it explicitly. As I said, you can use GCM in golang and java but if you don't want to use bouncy castle, you can use CBC mode in both languages.

    – Hamidreza Kalantari
    Mar 27 at 9:05

















  • Here I want to know what is the default mode which my java code is using and how to replicate the same in golang.

    – Prashant Gupta
    Mar 27 at 8:59











  • @PrashantGupta relying on default mode is risky. You should set it explicitly. As I said, you can use GCM in golang and java but if you don't want to use bouncy castle, you can use CBC mode in both languages.

    – Hamidreza Kalantari
    Mar 27 at 9:05
















Here I want to know what is the default mode which my java code is using and how to replicate the same in golang.

– Prashant Gupta
Mar 27 at 8:59





Here I want to know what is the default mode which my java code is using and how to replicate the same in golang.

– Prashant Gupta
Mar 27 at 8:59













@PrashantGupta relying on default mode is risky. You should set it explicitly. As I said, you can use GCM in golang and java but if you don't want to use bouncy castle, you can use CBC mode in both languages.

– Hamidreza Kalantari
Mar 27 at 9:05





@PrashantGupta relying on default mode is risky. You should set it explicitly. As I said, you can use GCM in golang and java but if you don't want to use bouncy castle, you can use CBC mode in both languages.

– Hamidreza Kalantari
Mar 27 at 9:05






Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55370699%2fgetting-different-result-cyphertext-while-using-aes-in-java-and-golang%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현