Skip to content

Instantly share code, notes, and snippets.

@melvyniandrag
Last active November 7, 2017 17:55
Show Gist options
  • Save melvyniandrag/d9565596e41401bbeb1e164b41599085 to your computer and use it in GitHub Desktop.
Save melvyniandrag/d9565596e41401bbeb1e164b41599085 to your computer and use it in GitHub Desktop.
aes 256 in grypt / java
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
public class Test{
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
String hw = "abcdefghabcdefgh";
System.out.println("************** Original Stuff *****************");
System.out.println( hw );
System.out.println("***********************************************");
String encoded = encrypt( hw );
String decoded = decrypt( encoded );
}
private static byte[] s_key = {
'1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6',
'1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6'
};
private static String encryptionType = "AES_256/ECB/NoPadding";
public static String encrypt(String strToEncrypt)
{
try
{
Cipher cipher = Cipher.getInstance( encryptionType );
SecretKeySpec key = new SecretKeySpec(s_key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
// I don't know why but in several examples I've seen online they Base64 encode the returned byte array instead of just returning the byte array. Why is that?
byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes());
System.out.println("************* Encrypted Stuff *****************");
System.out.println( bytesToHex( encryptedBytes ) );
System.out.println("***********************************************");
final String encryptedString = Base64.getEncoder().encodeToString( encryptedBytes );
return encryptedString;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static String decrypt(String strToDecrypt)
{
try
{
Cipher cipher = Cipher.getInstance( encryptionType );
SecretKeySpec key = new SecretKeySpec(s_key, "AES");
cipher.init(Cipher.DECRYPT_MODE, key);
final byte[] decryptedBytes = cipher.doFinal( Base64.getDecoder().decode( strToDecrypt ) );
final String decryptedString = new String( decryptedBytes );
System.out.println("************* Decrypted Stuff *****************");
System.out.println( decryptedString );
System.out.println("***********************************************");
return decryptedString;
}
catch( Exception e )
{
e.printStackTrace();
}
return null;
}
public static byte[] encryptNoEncode(String strToEncrypt)
{
try
{
Cipher cipher = Cipher.getInstance( encryptionType );
SecretKeySpec key = new SecretKeySpec(s_key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
// I don't know why but in several examples I've seen online they Base64 encode the returned byte array instead of just returning the byte array. Why is that?
return cipher.doFinal(strToEncrypt.getBytes());
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static String decryptNoDecode( byte[] strToDecrypt)
{
try
{
Cipher cipher = Cipher.getInstance( encryptionType );
SecretKeySpec key = new SecretKeySpec(s_key, "AES");
cipher.init(Cipher.DECRYPT_MODE, key);
final byte[] decryptedBytes = cipher.doFinal( strToDecrypt );
final String decryptedString = new String( decryptedBytes );
return decryptedString;
}
catch( Exception e )
{
e.printStackTrace();
}
return null;
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 3];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 3] = hexArray[v >>> 4];
hexChars[j * 3 + 1] = hexArray[v & 0x0F];
hexChars[j * 3 + 2] = ' ';
}
return new String(hexChars);
}
}
/**
* This code will encrypt some data and store it to a file.
* The data will then be read by a decryptor and decrypted.
* We will compare to see if another process can decrypt it.
*/
#include <cassert>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <gcrypt.h>
#include <string>
void closeHandle( gcry_cipher_hd_t &handle )
{
gcry_cipher_close( handle );
}
char _s_gKey[32]{
'1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6',
'1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6'
};
void printCharsAsHex( const char* charArr, const int encryptedSize )
{
std::stringstream ss;
for(int i = 0; i < encryptedSize; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << int((unsigned char)charArr[i]) << " ";
}
ss << "\n";
std::cout << "*****************EncryptedData********************" << std::endl;
std::cout << ss.str() << std::endl;
std::cout << "**************************************************" << std::endl;
}
void openHandle( gcry_cipher_hd_t &handle, uint32_t &blkLength )
{
gcry_error_t err = GPG_ERR_NO_ERROR;
const gcry_cipher_algos MyCipher = GCRY_CIPHER_AES256;
const uint32_t KeyLength = gcry_cipher_get_algo_keylen( MyCipher );
assert( KeyLength == 32 );
blkLength = gcry_cipher_get_algo_blklen( MyCipher );
static bool s_isCipherInitialized = false;
if ( s_isCipherInitialized == false )
{
static_cast<void>( gcry_control( GCRYCTL_ANY_INITIALIZATION_P ) );
static_cast<void>( gcry_control( GCRYCTL_DISABLE_SECMEM, 0 ) );
static_cast<void>( gcry_control( GCRYCTL_INITIALIZATION_FINISHED ) );
s_isCipherInitialized = true;
}
err = gcry_cipher_open( &handle, MyCipher, GCRY_CIPHER_MODE_ECB, 0 );
err = gcry_cipher_setkey( handle, _s_gKey, KeyLength );
}
int main(int argc, char** argv){
uint32_t data_ptr_buf_len = 16;
char data[data_ptr_buf_len + 1]{'a','b','c','d','e','f','g','h','a','b','c','d','e','f','g','h', '\0'};
std::cout << "**************** Original Data*******************" << std::endl;
std::cout << data << std::endl;
std::cout << "*************************************************" << std::endl;
gcry_cipher_hd_t handle;
memset(&handle, 0, sizeof(handle));
uint32_t blkLength = 0;
openHandle( handle, blkLength );
gcry_error_t err = GPG_ERR_NO_ERROR;
err = gcry_cipher_encrypt(handle, data, data_ptr_buf_len, NULL, 0);
closeHandle(handle);
printCharsAsHex( data, data_ptr_buf_len );
openHandle(handle, blkLength);
err = gcry_cipher_decrypt(handle, data, data_ptr_buf_len, NULL, 0);
closeHandle(handle);
std::string s(data);
std::cout << "*************** Decrypted Data *******************" << std::endl;
std::cout << s << std::endl;
std::cout << "**************************************************" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment