aes gcm解密问题(把java解密函数转换成C++版本) 5C

val nonce = reader.readBits(96)

val tag = reader.readBits(128)
val ciphertext = reader2.readBits(bitsLeft)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")

val keySpec = SecretKeySpec(EncryptionToken, "AES")

val paramSpec = GCMParameterSpec(128, nonce)

cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);

cipher.update(ciphertext)

val plaintext = cipher.doFinal(tag)

这是kotlin代码,用的是java的解密库
求高手翻译成C++版,用现成的解密库也可以

我的C++
val nonce = reader.ReadBits(96);
val tag = reader.ReadBits(128);
var bitsLeft = reader.GetBitsLeft();
val ciphertext = reader2.ReadBits(bitsLeft);
int ciphelegth = bitsLeft/8;
std::vector out_tmp;
out_tmp.resize(ciphelegth);
mbedtls_gcm_context ctx;
mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
mbedtls_gcm_init(&ctx);
int ret = mbedtls_gcm_setkey(&ctx, cipher, (unsigned char*)EncryptionToken.c_str(),
128);
uint8 iv[16];
memset(iv, 0, 16);
memcpy(iv, &nonce[0], 12);
ret = mbedtls_gcm_crypt_and_tag(&ctx, MBEDTLS_GCM_DECRYPT, ciphelegth, iv,
12, NULL, 0, &ciphertext[0], &out_tmp[0], 16, &tag[0]);

                ret 也是0,但是数据是不对的,请高手看看为什么调用失败

1个回答

val nonce = reader.readBits(96)

val tag = reader.readBits(128)
val ciphertext = reader2.readBits(bitsLeft)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")

val keySpec = SecretKeySpec(EncryptionToken, "AES")

val paramSpec = GCMParameterSpec(128, nonce)

cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);

cipher.update(ciphertext)

val plaintext = cipher.doFinal(tag)

这是kotlin代码,用的是java的解密库
求高手翻译成C++版,用现成的解密库也可以

我的C++
val nonce = reader.ReadBits(96);
val tag = reader.ReadBits(128);
var bitsLeft = reader.GetBitsLeft();
val ciphertext = reader2.ReadBits(bitsLeft);
int ciphelegth = bitsLeft/8;
std::vector out_tmp;
out_tmp.resize(ciphelegth);
mbedtls_gcm_context ctx;
mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
mbedtls_gcm_init(&ctx);
int ret = mbedtls_gcm_setkey(&ctx, cipher, (unsigned char*)EncryptionToken.c_str(),
128);
uint8 iv[16];
memset(iv, 0, 16);
memcpy(iv, &nonce[0], 12);
ret = mbedtls_gcm_crypt_and_tag(&ctx, MBEDTLS_GCM_DECRYPT, ciphelegth, iv,
12, NULL, 0, &ciphertext[0], &out_tmp[0], 16, &tag[0]);

                ret 也是0,但是数据是不对的,请高手看看为什么调用失败
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
aes gcm解密问题(把java解密函数转换成C++版本)

val nonce = reader.readBits(96) val tag = reader.readBits(128) val ciphertext = reader2.readBits(bitsLeft) val cipher = Cipher.getInstance("AES/GCM/NoPadding") val keySpec = SecretKeySpec(EncryptionToken, "AES") val paramSpec = GCMParameterSpec(128, nonce) cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec); cipher.update(ciphertext) val plaintext = cipher.doFinal(tag) 这是kotlin代码,用的是java的解密库 求高手翻译成C++版,用现成的解密库也可以 我的C++ val nonce = reader.ReadBits(96); val tag = reader.ReadBits(128); var bitsLeft = reader.GetBitsLeft(); val ciphertext = reader2.ReadBits(bitsLeft); int ciphelegth = bitsLeft/8; std::vector<uint8> out_tmp; out_tmp.resize(ciphelegth); mbedtls_gcm_context ctx; mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES; mbedtls_gcm_init(&ctx); int ret = mbedtls_gcm_setkey(&ctx, cipher, (unsigned char*)EncryptionToken.c_str(), 128); uint8 iv[16]; memset(iv, 0, 16); memcpy(iv, &nonce[0], 12); ret = mbedtls_gcm_crypt_and_tag(&ctx, MBEDTLS_GCM_DECRYPT, ciphelegth, iv, 12, NULL, 0, &ciphertext[0], &out_tmp[0], 16, &tag[0]); ret 也是0,但是数据是不对的,请高手看看为什么调用失败

Python中的AES-GCM解密

<div class="post-text" itemprop="text"> <p>I am trying to decrypt cipher text generated from AES_GCM. The cipher text was generated from "crypto/aes" library in golang. Now, I am trying to decipher the encrypted text in python using cryptodome library.</p> <pre><code>func AESEncryption(key []byte, plaintext []byte)([]byte, error){ c, err := aes.NewCipher(key) if err != nil { log.Printf("Error ocurred in generating AES key %s", err) return nil, err } gcm, err := cipher.NewGCM(c) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { log.Printf("Error ocurred in generating AES key %s", err) return nil, err } return gcm.Seal(nonce, nonce, plaintext, nil), nil } </code></pre> <p>plainText := "I will become what I deserve, Is there anything like freewil?"</p> <p>Hex encoded key : e629ed98829a893899ddda67f582ede72e2a187dd1ddd5ada54f49cfe2c8675f</p> <p>hex encoded encypted text = 9012a33bfb0a51dec4f96404cdd7300ec6afca1fa0d6679a7c036652d014a38faf909e9c44d08dffac121aa85d48b7256fa74542e2545e27dc070adfc03af26f2a32f50c2c311d5c91ff6de2ca3b4347da70669575c9b198f4 Deciphering the encrypted text in golang executes successfully but not in python.</p> <p>Code for decryption in python.</p> <pre><code>cipher = AES.new(binascii.unhexlify(key), AES.MODE_GCM) cipher.nonce = binascii.unhexlify(nonce) cipher.decrypt(binascii.unhexlify(hex_encoded_encrypted_hex)) </code></pre> </div>

从PHP到Golang的aes-256-gcm解密

<div class="post-text" itemprop="text"> <p>I have an encryption function that I use in PHP</p> <pre><code>function Encrypt(?string $Content, string $Key): string { return openssl_encrypt($Content, 'aes-256-gcm', $Key, OPENSSL_RAW_DATA, $IV = random_bytes(16), $Tag, '', 16) . $IV . $Tag; } </code></pre> <p>Paired with a decryption function</p> <pre><code>function Decrypt(?string $Ciphertext, string $Key): ?string { if (strlen($Ciphertext) &lt; 32) return null; $Content = substr($Ciphertext, 0, -32); $IV = substr($Ciphertext, -32, -16); $Tag = substr($Ciphertext, -16); try { return openssl_decrypt($Content, 'aes-256-gcm', $Key, OPENSSL_RAW_DATA, $IV, $Tag); } catch (Exception $e) { return null; } } </code></pre> <p>I store data encrypted from the encryption function into my db, and now I'm trying to decrypt those same values in Go, but I'm getting <code>cipher: message authentication failed</code> and I can't figure out what I'm missing.</p> <pre><code>c := []byte(`encrypted bytes of sorts`) // the bytes from the db content := c[:len(c)-32] iv := c[len(c)-32 : len(c)-16] tag := c[len(c)-16:] block, err := aes.NewCipher(key[:32]) if err != nil { panic(err.Error()) } aesgcm, err := cipher.NewGCMWithNonceSize(block, 16) if err != nil { panic(err.Error()) } fmt.Println(aesgcm.NonceSize(), aesgcm.Overhead()) // making sure iv and tag are both 16 bytes plaintext, err := aesgcm.Open(nil, iv, append(content, tag...), nil) if err != nil { panic(err.Error()) } </code></pre> <p>It's worth noting that the key I'm using isn't 32 bytes (it's way bigger), as I didn't know the key needed/should be 32 bytes, so I'm not entirely sure what PHP is doing with it (as in truncating it to 32 vs hashing it with something having 32 bytes of output vs some other thing).</p> <p>Looking at the <code>Open</code> function from the Go source, it looks like the tag should be the last "tag size" bytes of the text, so that's why I'm appending the tag to the ciphertext after parsing the pieces.</p> <pre><code>// copied from C:\Go\src\crypto\cipher\gcm.go, Go version 1.11 func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { if len(nonce) != g.nonceSize { panic("cipher: incorrect nonce length given to GCM") } if len(ciphertext) &lt; gcmTagSize { return nil, errOpen } if uint64(len(ciphertext)) &gt; ((1&lt;&lt;32)-2)*uint64(g.cipher.BlockSize())+gcmTagSize { return nil, errOpen } tag := ciphertext[len(ciphertext)-gcmTagSize:] ciphertext = ciphertext[:len(ciphertext)-gcmTagSize] var counter, tagMask [gcmBlockSize]byte g.deriveCounter(&amp;counter, nonce) g.cipher.Encrypt(tagMask[:], counter[:]) gcmInc32(&amp;counter) var expectedTag [gcmTagSize]byte g.auth(expectedTag[:], ciphertext, data, &amp;tagMask) ret, out := sliceForAppend(dst, len(ciphertext)) if subtle.ConstantTimeCompare(expectedTag[:], tag) != 1 { // The AESNI code decrypts and authenticates concurrently, and // so overwrites dst in the event of a tag mismatch. That // behavior is mimicked here in order to be consistent across // platforms. for i := range out { out[i] = 0 } return nil, errOpen } g.counterCrypt(out, ciphertext, &amp;counter) return ret, nil } </code></pre> <hr> <p>PHP example using the functions above</p> <pre><code>$Key = 'outspoken outburst treading cramp cringing'; echo bin2hex($Enc = Encrypt('yeet', $Key)), '&lt;br&gt;'; // 924b3ba418f49edc1757f3fe88adcaa7ec4c1e7d15811fd0b712b0b091433073f6a38d7b var_export(Decrypt($Enc, $Key)); // 'yeet' </code></pre> <p>Go</p> <pre><code>c, err := hex.DecodeString(`924b3ba418f49edc1757f3fe88adcaa7ec4c1e7d15811fd0b712b0b091433073f6a38d7b`) if err != nil { panic(err.Error()) } key := []byte(`outspoken outburst treading cramp cringing`) content := c[:len(c)-32] iv := c[len(c)-32 : len(c)-16] tag := c[len(c)-16:] block, err := aes.NewCipher(key[:32]) if err != nil { panic(err.Error()) } aesgcm, err := cipher.NewGCMWithNonceSize(block, 16) if err != nil { panic(err.Error()) } ciphertext := append(content, tag...) // or `ciphertext := content`, same error plaintext, err := aesgcm.Open(nil, iv, ciphertext, nil) if err != nil { panic(err.Error()) // panic: cipher: message authentication failed } </code></pre> </div>

Go中的AES-GCM + Base64后无法解密

<div class="post-text" itemprop="text"> <h1>Situation</h1> <p>I'm trying to implement a structure (the <code>CryptoService</code>) hiding en/decryption from the main program flow. I have implemented "normal" functions and base64 variants that should encode the cipher to it's base64 equivalent and visa-versa in decryption. This is done because our internal network protocol uses line-feed <code> </code> as delimiter.</p> <p><em>See code of implementation below</em></p> <h1>Problem</h1> <p>After writing the code below i started testing it. At first it went well and en- and decryption worked but soon I started noticing "randomly occurring" errors during the decryption process: <code>cipher: message authentication failed</code>. Now the important fact: the errors <strong>ONLY</strong> returned from the <code>DecryptBase64</code> func. But the base64 usage in go is pretty straight-forward and not much to worry about so I don't have any idea where the problems lies.</p> <h1>Code</h1> <p>Below you see the code for my <code>CryptoService</code> implementation and the associated test file. I have tried to clean the code up as much as possible (remove comments, additional input checks, etc.) without removing context. Nevertheless it's much code so thanks to all that read it - really appreciate your help!</p> <p><strong><code>cryptoservice.go</code></strong></p> <pre><code>type CryptoService struct { gcm cipher.AEAD } func NewCryptoService(key []byte) (cs *CryptoService, err error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } return &amp;CryptoService{ gcm: gcm, }, nil } func (cs CryptoService) Encrypt(plain []byte) (cipher []byte, err error) { nonce := make([]byte, cs.gcm.NonceSize()) _, err = io.ReadFull(rand.Reader, nonce) if err != nil { return nil, err } cipher = cs.gcm.Seal(nil, nonce, plain, nil) cipher = append(nonce, cipher...) return cipher, nil } func (cs CryptoService) EncryptBase64(plain []byte) (base64Cipher []byte, err error) { cipher, err := cs.Encrypt(plain) if err != nil { return nil, err } base64Cipher = make([]byte, base64.StdEncoding.EncodedLen(len(cipher))) base64.StdEncoding.Encode(base64Cipher, cipher) return } func (cs CryptoService) Decrypt(cipher []byte) (plain []byte, err error) { nonce := cipher[0:cs.gcm.NonceSize()] ciphertext := cipher[cs.gcm.NonceSize():] plain, err = cs.gcm.Open(nil, nonce, ciphertext, nil) if err != nil { return nil, err } return } func (cs CryptoService) DecryptBase64(base64Cipher []byte) (plain []byte, err error) { cipher := make([]byte, base64.StdEncoding.DecodedLen(len(base64Cipher))) _, err = base64.StdEncoding.Decode(cipher, base64Cipher) if err != nil { return nil, err } return cs.Decrypt(cipher) } </code></pre> <p><strong><code>cryptoservice_test.go</code></strong></p> <ul> <li><code>TestCryptoService_EncryptDecryptRoundtrip</code> works fine</li> <li><code>TestCryptoService_EncryptBase64DecryptBase64Roundtrip</code> fails "sometimes" (also note that it doesn't always fail on the same test-cases)</li> </ul> <p>Additional info: The <code>FastRandomString(n int)</code> func in the Dynamic-Test-Case creation is effectively only a copy-and-past from the accepted answer at: <a href="https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang">How to generate a random string of a fixed length in golang?</a></p> <pre><code>func TestCryptoService_EncryptDecryptRoundtrip(t *testing.T) { tests := []struct { name string aeskey string text string }{ {"Simple 1", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", "Text"}, {"Simple 2", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", "Some random content"}, {"Simple 3", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."}, {"Dynamic 1", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(32)}, {"Dynamic 2", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(1024)}, {"Dynamic 3", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(1024 * 64)}, {"Dynamic 4", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(1024 * 256)}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for i := 0; i &lt; 1000; i++ { key, _ := hex.DecodeString(tt.aeskey) cs, _ := NewCryptoService(key) cipher, err := cs.Encrypt([]byte(tt.text)) if err != nil { t.Errorf("CryptoService.Encrypt() error = %v", err) return } plain, err := cs.Decrypt(cipher) if err != nil { t.Errorf("CryptoService.Decrypt() error = %v", err) return } plainStr := string(plain) if plainStr != tt.text { t.Errorf("CryptoService.Decrypt() plain = %v, want = %v", plainStr, tt.text) return } } }) } } func TestCryptoService_EncryptBase64DecryptBase64Roundtrip(t *testing.T) { tests := []struct { name string aeskey string text string }{ {"Simple 1", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", "Text"}, {"Simple 2", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", "Some random content"}, {"Simple 3", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."}, {"Dynamic 1", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(32)}, {"Dynamic 2", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(1024)}, {"Dynamic 3", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(1024 * 64)}, {"Dynamic 4", "c4cc0dfc4ae0e45c045727f84ffd373127453bc232230bf1386972ac692436c1", FastRandomString(1024 * 256)}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for i := 0; i &lt; 1000; i++ { key, _ := hex.DecodeString(tt.aeskey) cs, _ := NewCryptoService(key) cipher, err := cs.EncryptBase64([]byte(tt.text)) if err != nil { t.Errorf("CryptoService.EncryptBase64() error = %v", err) return } plain, err := cs.DecryptBase64(cipher) if err != nil { t.Errorf("CryptoService.DecryptBase64() error = %v", err) return } plainStr := string(plain) if plainStr != tt.text { t.Errorf("CryptoService.DecryptBase64() plain = %v, want = %v", plainStr, tt.text) return } } }) } } </code></pre> </div>

Java AES-256加密文件之后解密文件,文件被损坏

public static Cipher initAESCipher(String password, int cipherMode) { // 创建Key gen KeyGenerator keyGenerator = null; Cipher cipher = null; try { keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(256, new SecureRandom(password.getBytes())); SecretKey secretKey = keyGenerator.generateKey(); byte[] codeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(codeFormat, "AES"); cipher = Cipher.getInstance("AES/ECB/PKCS7Padding","BC"); // 初始化 cipher.init(cipherMode, key); return cipher; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); // To change body of catch statement use File | } catch (NoSuchPaddingException e) { e.printStackTrace(); // To change body of catch statement use File | } catch (InvalidKeyException e) { e.printStackTrace(); // To change body of catch statement use File | } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } ``` ``` public static void encrypt(File source, File target, String password) throws Exception { InputStream input = new FileInputStream(source); OutputStream ouput = new FileOutputStream(target); logger.debug("开始写入加密文件"); long start = System.currentTimeMillis(); CipherInputStream cipherInputStream = (CipherInputStream) encrypt(input, password); IOUtils.copy(cipherInputStream,ouput ); cipherInputStream.close(); input.close(); ouput.close(); logger.debug("完成文件加密,耗时:" + (System.currentTimeMillis() - start)); } ``` ``` public static InputStream encrypt(InputStream input, String password) { logger.debug("开始加密文件流"); long start = System.currentTimeMillis(); Cipher cipher = initAESCipher(password, Cipher.ENCRYPT_MODE); logger.debug("生成密钥耗时:" + (System.currentTimeMillis() - start)); Assert.notNull(cipher); // 以加密流写入文件 CipherInputStream cipherInputStream = new CipherInputStream(input, cipher); logger.debug("完成加密文件流,耗时:" + (System.currentTimeMillis() - start)); return cipherInputStream; } ``` ``` 目前发现加密DOCX,PPTX,ZIP等压缩类文件之后进行解密会产生头信息被损坏的现象,望各位大神提供下解决思路。

如何在Golang中使用AES256-GCM加密文件?

<div class="post-text" itemprop="text"> <p>AES256-GCM could be implemented in go as <a href="https://gist.github.com/cannium/c167a19030f2a3c6adbb5a5174bea3ff" rel="noreferrer">https://gist.github.com/cannium/c167a19030f2a3c6adbb5a5174bea3ff</a></p> <p>However, <code>Seal</code> method of interface <code>cipher.AEAD</code> has signature:</p> <pre><code>Seal(dst, nonce, plaintext, additionalData []byte) []byte </code></pre> <p>So for very large files, one must read all file contents into memory, which is unacceptable.</p> <p>A possible way is to implement <code>Reader</code>/<code>Writer</code> interfaces on <code>Seal</code> and <code>Open</code>, but shouldn't that be solved by those block cipher "modes" of AEAD? So I wonder if this is a design mistake of golang cipher lib, or I missed something important with GCM?</p> </div>

在Java和golang中使用AES时获得不同的结果(密文)

<div class="post-text" itemprop="text"> <p>I am trying to replicate the java code for AES encryption into Golang. However I am not getting the same output in golang</p> <p>I tried below code:</p> <p><strong>Java Code:</strong></p> <pre><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; } } </code></pre> <p><strong>Java code output:</strong> <em>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</em></p> <p><strong>Golang Code:</strong></p> <pre><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)) } </code></pre> <p><strong>Golang Code output:</strong> <em>Encrypted Text is : 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp</em></p> </div>

如何在Golang中使用rsa密钥对进行AES加密和解密

<div class="post-text" itemprop="text"> <p>I want to generate rsa key pair(public and private), and then use them for AES encryption and decryption.e.g. Public key for Encryption and private key for Decryption.I wrote a simple code for this, but the problem is that when i run this code i get this error:</p> <pre><code>crypto/aes: invalid key size 1639 </code></pre> <p>How can i resove this problem ?? My Encryption code is given bellow:</p> <pre><code>//genrarting private key privateKey, err := rsa.GenerateKey(rand.Reader, 2014) if err != nil { return } privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey) privateKeyBlock := pem.Block{ Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privateKeyDer, } privateKeyPem := string(pem.EncodeToMemory(&amp;privateKeyBlock)) //using privateKeyPem for encryption text := []byte("My name is Astaxie") ciphertext, err := encrypt(text, []byte(privateKeyPem)) if err != nil { // TODO: Properly handle error log.Fatal(err) } fmt.Printf("%s =&gt; %x ", text, ciphertext) //Definition of encrypt() func encrypt(plaintext []byte, key []byte) ([]byte, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(c) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return nil, err } return gcm.Seal(nonce, nonce, plaintext, nil), nil } </code></pre> </div>

使GoCM中的GCM / CBC密码可流式传输

<div class="post-text" itemprop="text"> <p>The GCM and CBC AES ciphers in Go can't be used along side with StreamWriter or StreamReader, which forces me to allocate the entire file into memory. Obviously, this is not ideal with large files.</p> <p>I was thinking of making them streamable, by allocation some fixed size of blocks into memory, and feeding them to GCM or CBC, but I'm assuming that is probably a bad idea, since there must be a reason they've been designed this way.</p> <p>Can someone explain why these operation modes can't be used without allocating the entire files into memory?</p> </div>

如何解密在nodejs中加密的golang中的AES256位密码?

<div class="post-text" itemprop="text"> <p>I encrypted a string in Node.js like this. </p> <pre><code>var cipher = crypto.createCipheriv( "aes256", "&lt;A Buffer of length 32&gt;", "79b67e539e7fcaefa7abf167de5c06ed" ); </code></pre> <p>I noticed that a buffer in nodejs is like hex but every 2 consecutive characters are paired. So, It's length is half of whatever will come out if I convert it to a hex. </p> <p>Example: </p> <p>Buffer:</p> <pre><code>&lt;Buffer c3 80 36 f6 51 57 cb 6d b0 e8 fd 85 5a a2 8a da 07 4b e7 19 17 d1 c8 ee dc 2a e4 d8 5e 3c 9d a6&gt; </code></pre> <p>Hex:</p> <pre><code>c38036f65157cb6db0e8fd855aa28ada074be71917d1c8eedc2ae4d85e3c9da6 </code></pre> <p>Now, The key I use in aes256 can not be of length 64. Here, Buffer's length is 32 and hex's length is 64. </p> <p>I want to decrypt this cipher in golang and I'll have to use this key and iv to decrypt it. </p> <p>aes in golang takes a length depending upon the size of key and when it sees a key of length 64 it throws an error that says, <code>Invalid key length</code>.</p> <p>How do I decrypt it in golang? There is my current program in go: <a href="https://play.golang.org/p/SoXOz3XIPK" rel="nofollow noreferrer">https://play.golang.org/p/SoXOz3XIPK</a></p> <pre><code>package main import ( "crypto/aes" "crypto/cipher" "fmt" "log" ) func main() { encKey := "c38036f65157cb6db0e8fd855aa28ada074be71917d1c8eedc2ae4d85e3c9da6" iv := "79b67e539e7fcaefa7abf167de5c06ed" cipherText := "c02eccfc514a0b7fae830586dd56e0fcebb81fc49f41fa6dedf099c3645793bef7ec7075eca30063f9c0ef395d5ee2d44e4f3490114280abb7cf86d6eb525e2ec9bd2b781388986480f8b3df95f7b10e" block, err := aes.NewCipher([]byte(encKey)) if err != nil { log.Fatalf("%s", err) } decrypter := cipher.NewCFBDecrypter(block, []byte(iv)) decrypted := make([]byte, 1000) decrypter.XORKeyStream(decrypted, []byte(cipherText)) fmt.Printf("%s ", string(decrypted)) } </code></pre> </div>

用Golang解密用Java加密的内容(无iv)

<div class="post-text" itemprop="text"> <p>Wenn I try to decrypt a string, encrypted in Java I get an error: <em>"cipher: message authentication failed"</em>. </p> <p>Does java <em>inputOffset</em> from <em>AESCipher.engineDoFinal(byte[] input, int inputOffset, int inputLen)</em> meens the same as the Go <em>nonceSize</em> in my code?</p> <p>And is "<em>NewGCMWithNonceSize</em>" a right one decoder for my issue?</p> <p>Thanks for help. <strong>Working solution:</strong></p> <p><strong>JAVA</strong></p> <pre><code>public static String encryptGCM(String data) throws CryptException { try { SecureRandom random = SecureRandom.getInstanceStrong(); byte[] iv = new byte[12]; random.nextBytes(iv); log.trace("IV: {}", Arrays.toString(iv)); Key key = generateGcmKey(); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.ENCRYPT_MODE, key, spec); byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8")); log.trace("encrypted: {}", Arrays.toString(cipherText)); byte[] result = new byte[cipherText.length + iv.length]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(cipherText, 0, result, iv.length, cipherText.length); log.trace("Not encoded result: {}", Arrays.toString(result)); return Base64.getEncoder().encodeToString(result); } catch (Exception ex) { log.error("Failure occured while encrypt text value!", ex); throw new CryptException(data, ex); } } private static Key generateGcmKey() throws CryptException { try { SecretKey originalKey = new SecretKeySpec(KEY.getBytes(), 0, KEY.getBytes().length, ALGO); log.trace("Encoded key: {}", Base64.getEncoder().encodeToString(originalKey.getEncoded())); return originalKey; } catch (Exception ex) { log.error("Failure occured while generate key!", ex); throw new CryptException("Failure occured while generate key!", ex); } } </code></pre> <p><strong>GO</strong></p> <pre><code>func decode(data string) (string, error) { ciphertext, _ := base64.StdEncoding.DecodeString(data) key, _ := base64.URLEncoding.DecodeString(decodeKey) c, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } gcm, err := cipher.NewGCM(c) if err != nil { return "", err } nonceSize := 12 if len(ciphertext) &lt; nonceSize { return "", errors.New("ciphertext too short") } nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] result, err := gcm.Open(nil, nonce, ciphertext, nil) if err != nil { return "", err } return string(result), nil } </code></pre> </div>

PHP AES 128位加密/解密

<div class="post-text" itemprop="text"> <p>I'm trying to understand how to AES encrypt a piece of text(16 bytes - 128 bits). This code is from <a href="http://php.net/manual/ro/function.openssl-encrypt.php" rel="nofollow noreferrer">php manual</a>:</p> <pre><code>$key = openssl_random_pseudo_bytes(32); $plaintext = "message to be encrypted"; $cipher = "aes-128-gcm"; if (in_array($cipher, openssl_get_cipher_methods())) { $ivlen = openssl_cipher_iv_length($cipher); $iv = openssl_random_pseudo_bytes($ivlen); $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag); //store $cipher, $iv, and $tag for decryption later $original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag); echo $original_plaintext." "; } </code></pre> <p>The only problem with this is that i don't really understand it. <code>$cipher</code> is <code>aes-128-gcm</code> but i'm getting a 32 bytes encryption. </p> <p>So my questions are: Can somebody help me understand how it actually works?</p> <p>Is it possible to make it 16 bytes/128 bites?</p> <p>And is it safe to store <code>$cipher</code>, <code>$iv</code>, <code>$key</code> and <code>$tag</code> into a MySQL database for later use? </p> <p>P.S: if i change <code>$key</code> length to <code>16</code> instead of <code>32</code> the final output of <code>$ciphertext</code> is still 32 bytes.</p> <p>Thank you!</p> </div>

在golang中对AES解密的紧急返回

<div class="post-text" itemprop="text"> <p>I have implemented AES encryption on an angular app which sends encrypted string to a REST api written in golang which then decrypts it to verify if its a valid key or not.</p> <p>Encryption and decryption is working on angular app and golang separately but rest API returns Panic when we decrypt string sent from angular app </p> <p>Following is my code on app to encrypt in component file</p> <pre><code>import * as CryptoJS from 'crypto-js'; var key = "NPZ8fvABP5pKwU3"; // passphrase used to encrypt let encrypted_text = CryptoJS.AES.encrypt('Hello World', 'NPZ8fvABP5pKwU3'); </code></pre> <p>When I decrypt it with following code it returns "Hello World" on angular app </p> <pre><code>var bytes = CryptoJS.AES.decrypt(encrypted_text.toString(), 'NPZ8fvABP5pKwU3'); var plaintext = bytes.toString(CryptoJS.enc.Utf8); console.log(plaintext); </code></pre> <p>It fails to return same text in rest api with following code in main.go file</p> <pre><code>package main import ( "crypto/aes" "crypto/cipher" "crypto/md5" "crypto/rand" "encoding/hex" "fmt" "io" ) func decrypt(data []byte, passphrase string) []byte { key := []byte(createHash(passphrase)) block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } gcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } nonceSize := gcm.NonceSize() nonce, ciphertext := data[:nonceSize], data[nonceSize:] plaintext, err := gcm.Open(nil, nonce, ciphertext, nil) if err != nil { panic(err.Error()) } return plaintext } func main() { key2 := "NPZ8fvABP5pKwU3" key3 := []byte("encrypted string from angular app") plaintext := decrypt(key3, key2) fmt.Printf(string(plaintext)) } func createHash(key string) string { hasher := md5.New() hasher.Write([]byte(key)) return hex.EncodeToString(hasher.Sum(nil)) } </code></pre> <p><a href="https://play.golang.org/p/iGYyg0RB-Zi" rel="nofollow noreferrer">https://play.golang.org/p/iGYyg0RB-Zi</a></p> <p>returned error </p> <pre><code>panic: cipher: message authentication failed </code></pre> </div>

为什么AES无法解密,PHP。 OpenSSL的

<div class="post-text" itemprop="text"> <p>I'm having problem with decrypting I have</p> <pre><code> $key="Gwu078980"; $cipher="aes-128-gcm"; $iv=md5($cipher); $text="yaw0"; $tag=""; echo $encrypted=openssl_encrypt($text, $cipher, $key, 0, $iv, $tag); echo $de_ciphertext=openssl_decrypt($encrypted, $cipher, $key, 0, $iv, $tag); </code></pre> <p>Output</p> <pre><code>ELRmWQ== yaw0 </code></pre> <p>So the <em>raw text</em> is <code>yaw0</code> and the <em>encrypted</em> is <code>ELRmWQ==</code> and the <em>decrypted</em> is <code>yaw0</code> so perfect.</p> <p>But when I manually copy the encrypted text and use it as</p> <pre><code>$encrypted ="ELRmWQ=="; </code></pre> <p>And I run the decryption the decryption returns null. Thanks in advance for anyone to help me out.</p> </div>

openssl EVP aes_256_cbc解密失败(c++)

我用openssl AES-CBC加密了一个字符串,然后把密文通过socket发送到另外一台电脑上解密,可是解密失败了,我原本以为是传输中丢失了数据,可是后来我把密文再发回到加密的那台电脑上就可以解密了,并且两台电脑的用的是相同的key和iv。可以排除是传输的问题,可是既然密钥和初始向量都相

Go加密与使用相同密钥和iv的Ruby加密不同

<div class="post-text" itemprop="text"> <p>I have the following Ruby code:</p> <pre><code>require 'base64' require 'openssl' data = '503666666' key = '4768c01c4f598828ef80d9982d95f888fb952c5b12189c002123e87f751e3e82' nonce = '4eFi6Q3PX1478767 ' nonce = Base64.decode64(nonce) c = OpenSSL::Cipher.new('aes-256-gcm') c.encrypt c.key = key c.iv = nonce result = c.update(data) + c.final tag = c.auth_tag puts Base64.encode64(result + tag) # =&gt; J3AVfNG84bz2UuXcfre7LVjSbMpX9XBq6g== </code></pre> <p>that I'm trying to replicate in Golang. Here's what I have so far:</p> <pre><code>package main import ( "fmt" "crypto/aes" "crypto/cipher" "encoding/base64" "encoding/hex" ) func main() { data := []byte("503666666") key, err := hex.DecodeString(`4768c01c4f598828ef80d9982d95f888fb952c5b12189c002123e87f751e3e82`) if err != nil { panic(err) } nonceB64 := "4eFi6Q3PX1478767 " nonce, err := base64.StdEncoding.DecodeString(nonceB64) if err != nil { panic(err) } block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } aesgcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } ciphertext := aesgcm.Seal(nil, nonce, data, nil) fmt.Printf("%s ", base64.StdEncoding.EncodeToString(ciphertext)) } </code></pre> <p>However the outcome from the Go version is: </p> <blockquote> <p>+S52HGbLV1xp+GnF0v8VNOqc5J2GY2+SqA==</p> </blockquote> <p>vs.</p> <blockquote> <p>J3AVfNG84bz2UuXcfre7LVjSbMpX9XBq6g== </p> </blockquote> <p>Why am I getting different results?</p> <p>Thanks,</p> </div>

Golang AES-CBC 256使用CryptoJS解密

<div class="post-text" itemprop="text"> <p>Been working for days trying to get Golang AES-CBC to CryptoJS working (or vice-versa), I fixed most of the errors but not getting decryption even though i have confirmed the key, iv, ciphertext is the same on both ends.</p> <p>There must be someone who knows, there is no working example anywhere on the net for this...</p> <pre><code>//golang if a == "test64bytes" { output = "AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDDAAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD" } // encrypt ajax response iv := decodeBase64("AAAAAAAAAAAAAAAAAAAAAA==") ciphertext := []byte(output) ckey := decodeBase64(string(PLAINkey[0:32])) c, err := aes.NewCipher(ckey) cfbdec := cipher.NewCBCDecrypter(c, iv) plaintext := make([]byte, len(ciphertext)) cfbdec.CryptBlocks(plaintext, ciphertext) crypt := string(encodeBase64(plaintext)) fmt.Fprintf(res, "%v", crypt) fmt.Println(encodeBase64(ckey)) fmt.Println(encodeBase64(iv)) fmt.Println(crypt) // javascript if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { var enc = {}; enc["key"] = CryptoJS.enc.Base64.parse(keyseed.substring(0,32)); enc["iv"] = CryptoJS.enc.Base64.parse("AAAAAAAAAAAAAAAAAAAAAA=="); enc["ciphertext"] = CryptoJS.enc.Base64.parse(xmlhttp.responseText); enc["salt"] = ""; console.log("RESPONSE:", xmlhttp.responseText, atob(xmlhttp.responseText)); // check i'm using same data console.log(CryptoJS.enc.Base64.stringify(enc["key"])); console.log(CryptoJS.enc.Base64.stringify(enc["iv"])); console.log(CryptoJS.enc.Base64.stringify(enc["ciphertext"])); var options = { keySize: 256 / 8, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: enc["iv"] }; de = CryptoJS.AES.decrypt(enc, enc["key"], options); document.getElementById(target).innerHTML = de.toString(); console.log(de.toString(CryptoJS.enc.Utf8)); console.log("DECRYPTION FINISHED"); } </code></pre> </div>

aes/cbc/pkcs5padding 加密在android4.4版本以下出错

以下加密在android4.4版本上运行正常,但是在低于4.4版本上的设备,每次结果不一样。希望有人能帮我解决这个问题,谢谢! public String encryptPass(){ String username="stackoverflow"; String password="stackoverflow"; String salt="stackoverflow145"; PBEKeySpec keySpec=new PBEKeySpec(username.toCharArray(),salt.getBytes(),1000,256); SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKey key=keyFactory.generateSecret(keySpec); /*初始向量:16位长度*/ byte[] iv={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} IvParameterSpec ivSpec=new IvParameterSpec(iv); Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec); byte[] passBytes=cipher.doFinal(password.getBytes()); String result=Base64.encodeToString(passBytes,Base64.NO_WRAP); return result; }

openssl AES-CBC 命令行使用

当使用: openssl enc -e -aes-128-cbc -iv 0b1e1d000f0b07091d1f04071f1e0407 -k 1234567812345678 -in inputor.xml -out input.xml 或者 openssl enc -e -aes-128-cbc -k 1234567812345678 -in inputor.xml -out input.xml 这两种方式的时候第一种是自己输入初始化变量iv值,那下面这种方式的iv值是什么呢?怎么计算的?

Golang使用AES加密数据

<div class="post-text" itemprop="text"> <p>I'm not sure if this is the right place to ask this. But I have no experience with C# and have been tasked to convert a security piece of code to Golang</p> <p>I was wondering if i'm missing out on something here. </p> <p>The C# code uses a <code>Rijndael</code> class to encrypt a bit of data. The <code>key</code> value and <code>iv</code> value is written out in the byte code like this</p> <pre><code> public static byte[] Key = new byte[]{0xx, 0xx, 0xx, 0xx, 0xx, 0xx4, 0xxx, 0xxx, 0xxx, 0xxx, xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx}; </code></pre> <p><code>public static byte[] IV = new byte[] // save structure as above with 16 in length</code></p> <p>then theres a bit of code which does this</p> <pre><code>Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(dataWithoutHeader, 0, dataWithoutHeader.Length); cs.Close(); </code></pre> <p>the function sends out <code>byte[] data</code> as output</p> <p>I'm trying to mimic this is <code>golang</code> like this</p> <pre><code>func StartEncryption(message []byte) []byte { var key = []byte {// same as C# } var iv = []byte{ // same as C# } var err error fmt.Printf(" length of key %+v , length of iv %+v ", len(key), len(iv)) // Encrypt encrypted := make([]byte, len(message)) err = EncryptAESCFB(encrypted, []byte(message), key, iv) if err != nil { panic(err) } return encrypted } </code></pre> <p>The Encryption function</p> <pre><code>func EncryptAESCFB(dst, src, key, iv []byte) error { aesBlockEncrypter, err := aes.NewCipher([]byte(key)) if err != nil { return err } aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv) aesEncrypter.XORKeyStream(dst, src) return nil } </code></pre> <p>The output of this is sent over an API whose output needs to be decrypted. I'm using this below</p> <pre><code>func decryptMessage(message []byte)error{ var key = []byte{ // same as C# } var iv = []byte{ // same as C# } // Remove the head part of the response (45 bytes) responseBody := message[45:] decrypted := make([]byte, len(responseBody)) err := DecryptAESCFB(decrypted, responseBody, key, iv) if err != nil { fmt.Printf(" error : %+v ", err) } return nil } func DecryptAESCFB(dst, src, key, iv []byte) error { aesBlockDecrypter, err := aes.NewCipher([]byte(key)) if err != nil { return nil } aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv) aesDecrypter.XORKeyStream(dst, src) return nil } </code></pre> <p>The decryptor gives me gibberish - Am i going wrong somewhere?</p> <p>My question boils down to 2 questions</p> <ol> <li><p>Would the C# function using the <code>rijndael</code> class and the golang functiony yield the same output or should i be doing something more/less</p></li> <li><p>Is the byte array the right data to store the key, IV in - i.e its not the same used in C# when copied to GO</p></li> </ol> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

立即提问
相关内容推荐