Golang Crypto Symmetric Key Generate

/ Comments off

Key derives a key from the password, salt, and cost parameters, returning a byte slice of length keyLen that can be used as cryptographic key. N is a CPU/memory cost parameter, which must be a power of two greater than 1. R and p must satisfy r. p. Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. Use the generateKey method of the SubtleCrypto interface to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). Syntax const result = crypto.subtle.generateKey(algorithm, extractable, keyUsages); Parameters. Algorithm is a dictionary object defining the type of key to generate and providing extra algorithm-specific.

Generate SSH RSA Private/Public Key pair with Golang
gistfile1.txt
// This shows an example of how to generate a SSH RSA Private/Public key pair and save it locally
package main
import (
'crypto/rand'
'crypto/rsa'
'crypto/x509'
'encoding/pem'
'golang.org/x/crypto/ssh'
'io/ioutil'
'log'
)
func main() {
savePrivateFileTo := './id_rsa_test'
savePublicFileTo := './id_rsa_test.pub'
bitSize := 4096
privateKey, err := generatePrivateKey(bitSize)
if err != nil {
log.Fatal(err.Error())
}
publicKeyBytes, err := generatePublicKey(&privateKey.PublicKey)
if err != nil {
log.Fatal(err.Error())
}
privateKeyBytes := encodePrivateKeyToPEM(privateKey)
err = writeKeyToFile(privateKeyBytes, savePrivateFileTo)
if err != nil {
log.Fatal(err.Error())
}
err = writeKeyToFile([]byte(publicKeyBytes), savePublicFileTo)
if err != nil {
log.Fatal(err.Error())
}
}
// generatePrivateKey creates a RSA Private Key of specified byte size
func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
// Private Key generation
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return nil, err
}
// Validate Private Key
err = privateKey.Validate()
if err != nil {
return nil, err
}
log.Println('Private Key generated')
return privateKey, nil
}
// encodePrivateKeyToPEM encodes Private Key from RSA to PEM format
func encodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
// Get ASN.1 DER format
privDER := x509.MarshalPKCS1PrivateKey(privateKey)
// pem.Block
privBlock := pem.Block{
Type: 'RSA PRIVATE KEY',
Headers: nil,
Bytes: privDER,
}
// Private key in PEM format
privatePEM := pem.EncodeToMemory(&privBlock)
return privatePEM
}
// generatePublicKey take a rsa.PublicKey and return bytes suitable for writing to .pub file
// returns in the format 'ssh-rsa ..'
func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {
publicRsaKey, err := ssh.NewPublicKey(privatekey)
if err != nil {
return nil, err
}
pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
log.Println('Public key generated')
return pubKeyBytes, nil
}
// writePemToFile writes keys to a file
func writeKeyToFile(keyBytes []byte, saveFileTo string) error {
err := ioutil.WriteFile(saveFileTo, keyBytes, 0600)
if err != nil {
return err
}
log.Printf('Key saved to: %s', saveFileTo)
return nil
}
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment
A basic example of how to perform symmetric key encryption/decryption using AES and Java's cryptography API.
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

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

Golang Generate Password

no brilliant tutorial !! /product-key-generator-windows-7-penalties.html.

commented Sep 8, 2018

Golang Crypto Example

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 Crypto Symmetric Key Generate Function

commented Feb 9, 2019

/windows-7-ultimate-product-key-generator-torrent.html. how do you generate the encryption key

Golang Crypto Sha256

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