Golang Crypto Symmetric Key Generate

Posted on by
A basic example of how to perform symmetric key encryption/decryption using AES and Java's cryptography API.
Golang Crypto Symmetric Key Generate
  1. It is recommended to use an authentication key with 32 or 64 bytes. The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes. How do I generate a 64 byte key, is it as straightforward as byte'64characterslongstring', I thought it is not always so straight forward?
  2. If the salt is of 0 length, it generates a new salt, and returns the expanded key and salt as byte arrays. A salt should only be provided as part of a decryption or verification process. When using ExpandKey to create a new key, let ExpandKey generate the salt. This is to lessen the risk of a weak or non-unique salt being used.
  3. HMAC can work with any existing message digest algorithms (hash functions). It considers the message digest produced by the embedded hash function as a black box. It then uses the shared symmetric key to encrypt the message digest, thus, producing the final output, that is, MAC.
  4. Fernet (symmetric encryption)¶ Fernet guarantees that a message encrypted using it cannot be manipulated or read without the key. Fernet is an implementation of symmetric (also known as “secret key”) authenticated cryptography. Fernet also has support for implementing key rotation via MultiFernet. Class cryptography.fernet.Fernet (key) source ¶.
CryptoHelper.java
importjava.security.Key;
importjava.security.SecureRandom;
importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importjavax.crypto.spec.IvParameterSpec;
importorg.apache.commons.codec.binary.Base64;
publicclassCryptoHelper {
publicstaticvoidmain( String [] args ) throwsException {
CryptoHelper crypto =newCryptoHelper();
String plaintext ='This is a good secret.';
System.out.println( plaintext );
String ciphertext = crypto.encrypt( plaintext );
System.out.println( ciphertext );
String decrypted = crypto.decrypt( ciphertext );
System.out.println( decrypted );
}
publicStringencrypt( Stringplaintext ) throwsException {
return encrypt( generateIV(), plaintext );
}
publicStringencrypt( byte [] iv, Stringplaintext ) throwsException {
byte [] decrypted = plaintext.getBytes();
byte [] encrypted = encrypt( iv, decrypted );
StringBuilder ciphertext =newStringBuilder();
ciphertext.append( Base64.encodeBase64String( iv ) );
ciphertext.append( ':' );
ciphertext.append( Base64.encodeBase64String( encrypted ) );
return ciphertext.toString();
}
publicStringdecrypt( Stringciphertext ) throwsException {
String [] parts = ciphertext.split( ':' );
byte [] iv =Base64.decodeBase64( parts[0] );
byte [] encrypted =Base64.decodeBase64( parts[1] );
byte [] decrypted = decrypt( iv, encrypted );
returnnewString( decrypted );
}
privateKey key;
publicCryptoHelper( Keykey ) {
this.key = key;
}
publicCryptoHelper() throwsException {
this( generateSymmetricKey() );
}
publicKeygetKey() {
return key;
}
publicvoidsetKey( Keykey ) {
this.key = key;
}
publicstaticbyte [] generateIV() {
SecureRandom random =newSecureRandom();
byte [] iv =newbyte [16];
random.nextBytes( iv );
return iv;
}
publicstaticKeygenerateSymmetricKey() throwsException {
KeyGenerator generator =KeyGenerator.getInstance( 'AES' );
SecretKey key = generator.generateKey();
return key;
}
publicbyte [] encrypt( byte [] iv, byte [] plaintext ) throwsException {
Cipher cipher =Cipher.getInstance( key.getAlgorithm() +'/CBC/PKCS5Padding' );
cipher.init( Cipher.ENCRYPT_MODE, key, newIvParameterSpec( iv ) );
return cipher.doFinal( plaintext );
}
publicbyte [] decrypt( byte [] iv, byte [] ciphertext ) throwsException {
Cipher cipher =Cipher.getInstance( key.getAlgorithm() +'/CBC/PKCS5Padding' );
cipher.init( Cipher.DECRYPT_MODE, key, newIvParameterSpec( iv ) );
return cipher.doFinal( ciphertext );
}
}

commented Dec 25, 2017

Jun 23, 2012  The RSA keys are just set to NULL because their values will be initialized later when the RSA/AES functions are called. The #ifdef line certainly peaks some interest. Since this class is eventually going to be dropped in a server, it will be using the client’s public key to encrypt data, but we don’t have a client yet, so we define a fake client and generate another RSA key. Package x509 parses X.509-encoded keys and certificates. Pkix Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.

Thank you! Thanks to you, I could do this.

commented Mar 8, 2018

Brilliant tutorial, just what I have been looking for

commented Jun 20, 2018

no brilliant tutorial !!

commented Sep 8, 2018

is this program an example of AES NI implementation? as there are no initialization vectors in NI .according to my understanding!
Kindly reply soon

Golang Generate Password

commented Feb 9, 2019

how do you generate the encryption key

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Secure context
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Jul 31, 2015  We tested this GTA 4 cd key generator before to make it public, and all that we can say is ‘Grab it NOW’. Grand Theft Auto IV Code Generator is updated everyday so you’ll not have problems, and is 100% safe, it use our Proxy and Anti-Ban Systems, So you don’t need to worry about your Rockstar,Origin or Steam account. Key Generator is one of the few working tools out there and why. Oct 15, 2013  Free gta v serial key is ready to be downloaded To Download GTA 5 KEY Generator No PASSWORD No SURVEY FrEEClick the download button Video Rating: 4 / 5. Gta iv key generator no survey download.

Use the generateKey() method of the SubtleCrypto interface to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).

Syntax

Parameters

  • algorithm is a dictionary object defining the type of key to generate and providing extra algorithm-specific parameters.
    • For RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP: pass an RsaHashedKeyGenParams object.
    • For ECDSA or ECDH: pass an EcKeyGenParams object.
    • For HMAC: pass an HmacKeyGenParams object.
    • For AES-CTR, AES-CBC, AES-GCM, or AES-KW: pass an AesKeyGenParams object.
  • extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey().
  • keyUsages  is an Array indicating what can be done with the newly generated key. Possible values for array elements are:
    • encrypt: The key may be used to encrypt messages.
    • decrypt: The key may be used to decrypt messages.
    • sign: The key may be used to sign messages.
    • verify: The key may be used to verify signatures.
    • deriveKey: The key may be used in deriving a new key.
    • deriveBits: The key may be used in deriving bits.
    • wrapKey: The key may be used to wrap a key.
    • unwrapKey: The key may be used to unwrap a key.

Return value

  • result is a Promise that fulfills with a CryptoKey (for symmetric algorithms) or a CryptoKeyPair (for public-key algorithms).

Exceptions

The promise is rejected when the following exception is encountered:

SyntaxError
Raised when the result is a CryptoKey of type secret or private but keyUsages is empty.
SyntaxError
Raised when the result is a CryptoKeyPair and its privateKey.usages attribute is empty.

Examples

RSA key pair generation

This code generates an RSA-OAEP encryption key pair. See the complete code on GitHub.

Elliptic curve key pair generation

This code generates an ECDSA signing key pair. See the complete code on GitHub.

HMAC key generation

This code generates an HMAC signing key. See the complete code on GitHub.

AES key generation

This code generates an AES-GCM encryption key. See the complete code on GitHub.

Specifications

SpecificationStatusComment
Web Cryptography API
The definition of 'SubtleCrypto.generateKey()' in that specification.
RecommendationInitial definition.

Browser compatibility

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub

Golang Crypto X509

DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
generateKeyChromeFull support 37EdgePartial support12
Partial support12
Notes
Notes Not supported: RSA-PSS, ECDSA, ECDH.
Notes Not supported: AES-CTR.
FirefoxFull support 34
Full support 34
No support32 — 34
Disabled From version 32 until version 34 (exclusive): this feature is behind the dom.webcrypto.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IEPartial support11
Notes
Partial support11
Notes Returns KeyOperation instead of Promise
OperaFull support 24SafariFull support 7WebView AndroidFull support 37Chrome AndroidFull support 37Firefox AndroidFull support 34
Full support 34
No support32 — 34
Disabled
Disabled From version 32 until version 34 (exclusive): this feature is behind the dom.webcrypto.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera AndroidFull support 24Safari iOSFull support 7Samsung Internet AndroidFull support 6.0

Golang Crypto Symmetric Key Generate Function

Legend

Full support Â
Full support
Partial support Â
Partial support
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

See also

Golang Crypto Symmetric Key Generate Key

  • Cryptographic key length recommendations.
  • NIST cryptographic algorithm and key length recommendations.