懂java和php来,aes加解密将java版转为php版

/**
* AES加密
*
* @param key
* 密钥信息
* @param content
* 待加密信息
*/
public static byte[] encodeAES(byte[] key, byte[] content) throws Exception {
// 不是16的倍数的,补足
int base = 16;
if (key.length % base != 0) {
int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(key, 0, temp, 0, key.length);
key = temp;
}

    SecretKey secretKey = new SecretKeySpec(key, "AES");
    IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    byte[] tgtBytes = cipher.doFinal(content);
    return tgtBytes;
}

1个回答

google下,有转换工具可以转换代码的。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Golang中的AES加密和Java中的解密

<div class="post-text" itemprop="text"> <p>I have the following AES Encryption function written in Golang.</p> <pre><code>func encrypt(key []byte, text string) string { plaintext := []byte(text) block, err := aes.NewCipher(key) if err != nil { panic(err) } ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { panic(err) } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) return base64.URLEncoding.EncodeToString(ciphertext) } </code></pre> <p>I am struggling to understand the flow to decrypt the generated text using Java. Any help will be highly appreciated!</p> <p>Here is the Scala code, Not sure what's the problem with it.</p> <pre><code>def decode(input:String) = { val keyBytes = Hex.decodeHex("someKey".toCharArray) val inputWithoutPadding = input.substring(0,input.size - 2) val inputArr:Seq[Byte] = Hex.decodeHex(inputWithoutPadding.toCharArray) val skSpec = new SecretKeySpec(keyBytes, "AES") val iv = new IvParameterSpec(inputArr.slice(0,16).toArray) val dataToDecrypt = inputArr.slice(16,inputArr.size) val cipher = Cipher.getInstance("AES/CFB/NoPadding") cipher.init(Cipher.DECRYPT_MODE, skSpec, iv) cipher.doFinal(dataToDecrypt.toArray) } </code></pre> </div>

关于PHP和JAVA之间的AES加密互通问题

公司今日接到一个需求,要与银行方面进行对接,接收银行方面 推送过来的加密信息,解密后入库进行统计,由于银行方是JAVA环境,我司是PHP环境,所以需要写一个PHP的解密方法,查阅各种文档后还是无法满足需求,无法进行解密,特来求助. 银行方只有一个加密流程文档: 加密方式:AES/ECB/PKCS5Padding 1、将data中的字段转成json格式如下: ``` {"userId":"12345678911111233","state":"2","cardNo":"625966","time":"20171212","extInfo":""} ``` 2、URLEncode对josn字符串进行编码UTF-8防止中文乱码 ``` URLEncoder.encode(data, "UTF-8") %7B%22userId%22%3A%2212345678911111233%22%2C%22state%22%3A%222%22%2C%22cardNo%22%3A%22625966%22%2C%22time%22%3A%2220171212%22%2C%22extInfo%22%3A%22%22%7D ``` 3、使用aesKey对URLEncode后的字符串进行AES加密, 得到data: ``` aesKey=Spdbccc-testtest XBD5nXa7oAnsWo/l843zUfmuhpmWGKEieJoJXxZEHPun1zfQhEPBFKv5kXZMM8i2Vr9RJwZeW/zn6OScGSlRTNVaytu2M5CDABw6B1grqxCqjTu/fKTp3hpMJd0riMB7H7ZK5xGUBu2nGgacjPmVcVl8Xm34fdArx17DkHbHqOWgiwmesk0C/lgKK7hkyuiuVtEQPmc02Ipjx3JGyJ+59g== ``` 我这边先是按照查询的文档中所说直接使用PHP自带的mcrypt扩展进行解密,发现php7.2已经弃用该扩展,换成openssl方式使用AES-128-ECB进行解密返回值是false;后来我转变思路,先用openssl以AES-128-ECB模式对第二步的串进行加密,获取到的结果和步骤三中的完全不一样,我改用先获取openssl的加密模式列表然后循环加密,输出各个加密方式的结果,发现没有一个能对上,到此以我的水平已经不知道该如何进行下一步了,特来求助!

使用相同密钥的AES加密在Java和PHP中生成不同的值

<div class="post-text" itemprop="text"> <p>In PHP, I am unable to decrypt a string encrypted in java using AES CBC 128 bit. I have tried bott phpseclib and openssl on the PHP side. Though my preference is for phpseclib.</p> <p><strong>Java Side</strong></p> <ol> <li><p>I generated an AES 128 bit key using:</p> <pre><code>keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); secretKey = keyGen.generateKey(); </code></pre></li> <li><p>Generated an initialization vector by getting bytes from a string:</p> <pre><code>byte[] iv = "myuniqueivparam".getBytes("UTF-8"); </code></pre></li> <li><p>Encrypted a string as follows:</p> <pre><code>Cipher enCipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); </code></pre> <p>// the key and iv are passed on to php as strings</p></li> </ol> <p><strong>PHP side</strong></p> <ol> <li><p>Set the algorithm:</p> <pre><code>$aes = new Crypt_AES(CRYPT_AES_MODE_CBC); </code></pre></li> <li><p>The key and iv I got from java are passed as strings:</p> <pre><code>$aes-&gt;setKey($userKey); $aes-&gt;setKeyLength(128); // when I echo this I get myuniqueivparam $ivdecode=base64_decode($iv); $aes-&gt;setIV($ivdecode); </code></pre></li> <li><p>Set the same input and add padding</p> <pre><code>$input="winning"; $blocksize = 16; $pad1=$blocksize -(strlen($input) %$blocksize); $input1=$input . str_repeat(chr($pad1), $pad1); </code></pre></li> <li><p>Encrypted the string using phpseclib:</p> <pre><code>$aes = new Crypt_AES(CRYPT_AES_MODE_CBC); $dummy = base64_encode($aes-&gt;encrypt($input1)); echo $dummy; </code></pre></li> <li><p><code>$decryptedstring=$aes-&gt;decrypt($encryptedStringInJava);</code></p></li> </ol> <p><strong>Issues</strong></p> <ol> <li><p>When I print <code>$dummy</code>, in step 4, the encrypted string that I get does not match the encrypted string from java.</p></li> <li><p>Decrypting <code>$encryptedStringInJava</code> is not working in PHP (step 5)</p></li> </ol> <p>I have tried encryption/decryption in java using both phpseclib and openssl. </p> </div>

使用Java和PHP的AES CBC 128位加密

<div class="post-text" itemprop="text"> <p>I have recently used the AES CBC 128 algorithm in Java in order to cipher data. Now I need to rebuild that algorithm in PHP, but I have no idea how, because PHP algorithms on the internet return different results. Maybe you can help me. </p> <p>This is the Java-code to encrypt:</p> <pre><code>private SecretKeySpec secretKey; private IvParameterSpec ivSpec; public void setKey(String myKey) { MessageDigest sha = null; try { byte[] key = myKey.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new SecretKeySpec(key, "AES"); byte[] iv = new String("1010101010101010").getBytes("UTF-8"); ivSpec = new IvParameterSpec(iv); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public String encrypt(String strToEncrypt) { try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); return Base64.encode(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); } catch (Exception e) { e.printStackTrace(); } return null; } public String decrypt(String strToDecrypt) { try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); return new String(cipher.doFinal(Base64.decode(strToDecrypt))); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { AESText aes = new AESText(); final String secretKey = "com.secure.test.projectjasdS/FjkGkGhkGjhG786Vjfg=tjGFGH"; aes.setKey(secretKey); String originalString = "test set se ts et set s et se"; String encryptedString = aes.encrypt(originalString); String decryptedString = aes.decrypt(encryptedString); System.out.println("origin: " + originalString); System.out.println("encrypted: " + encryptedString); System.out.println("decrypted: " + decryptedString); } </code></pre> <p>This is my php code:</p> <pre><code> protected $key; protected $method = 'AES-128-CBC'; protected $iv = '1010101010101010'; protected $option = OPENSSL_CIPHER_AES_128_CBC; function __construct($key) { $this-&gt;key = $key; } public function encrypt($data) { if (is_null($data)) { return "Error " . INVALID_PARAMS_ENCRYPTIONS . ": Data is null "; } $enc = openssl_encrypt($data, $this-&gt;method, $this-&gt;key, $this-&gt;option, $this-&gt;iv); return base64_encode($enc); } public function decrypt($data) { if (is_null($data)) { return "Error " . INVALID_PARAMS_ENCRYPTIONS . ": Data is null "; } $data = base64_decode($data); $dec = openssl_decrypt($data, $this-&gt;method, $this-&gt;key, $this-&gt;option, $this-&gt;iv); return $dec; } </code></pre> <p>When I encrypted data from java encryption, This result cannot decrypt on Php decryption.</p> <p>Can you guys possibly help me with building a PHP script, that returns the same results with java encryption?</p> </div>

用C#解密JAVA的AES加密字符串

附JAVA的加密方法 public static String encrypt(String s, String token) { try { byte[] key = Hex.toBytes(token); return encryptBase64URLSafe(s, key); } catch (Exception e) { // e.printStackTrace(); return null; } } public static byte[] toBytes(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); } return data; } private static String encryptBase64URLSafe(String s, byte[] key) { BaseEncoding b64 = BaseEncoding.base64Url().omitPadding(); byte[] encryptedBytes = encryptBytes(s, key); return b64.encode(encryptedBytes); } private static byte[] encryptBytes(String s, byte[] key) { if (key == null) { return null; } // 判断Key是否为16位 if (key.length != 16) { return null; } SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(s.getBytes("utf-8")); return encrypted; } catch (Exception e) { return null; } } 这个用C#怎么解密啊,大家帮帮忙,我尝试了很多方法都不行 在Convert.FromBase64String(encryptedText);时就报错

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等压缩类文件之后进行解密会产生头信息被损坏的现象,望各位大神提供下解决思路。

使用Go和PHP进行AES加密

<div class="post-text" itemprop="text"> <p>I am using AES encryption in Go and PHP. But both the languages does not encrypt/decrypt each other ciphertext. Following i have tried in php</p> <pre><code> class Crypto { private $encryptKey = "keyforencryption"; private $iv = 'ivusedforencrypt'; private $blocksize = 16; public function encrypt($toEncrypt){ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB); //$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); return base64_encode($this-&gt;iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this-&gt;encryptKey, $toEncrypt, MCRYPT_MODE_CFB, $this-&gt;iv)); } public function decrypt($toDecrypt){ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CFB);//$this-&gt;blocksize; $toDecrypt = base64_decode($toDecrypt); return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this-&gt;encryptKey, substr($toDecrypt, $iv_size), MCRYPT_MODE_CFB, substr($toDecrypt, 0, $iv_size))); } } $c = new Crypto(); echo "Encrypted : ".$e = $c-&gt;encrypt("test"); echo "&lt;br/&gt;Decrypted : ".$c-&gt;decrypt($e); </code></pre> <p>output : aXZ1c2VkZm9yZW5jcnlwdDpdZEinU2rB</p> <p>and this one in Go with AES</p> <pre><code> package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "errors" "fmt" "io" "log" ) func main() { key := []byte("keyforencryption") plaintext := []byte("test") fmt.Printf("%s ", plaintext) ciphertext, err := encrypt(key, plaintext) if err != nil { log.Fatal(err) } b := base64.StdEncoding.EncodeToString(ciphertext) fmt.Printf("Encrypted text : %s ", b) result, err := decrypt(key, b) if err != nil { log.Fatal(err) } fmt.Printf("Decrypted Text : %s ", result) } func encrypt(key, text []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } //b := base64.StdEncoding.EncodeToString(text) ciphertext := make([]byte, aes.BlockSize+len(text)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil, err } cfb := cipher.NewCFBEncrypter(block, iv) cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(text)) return ciphertext, nil } func decrypt(key []byte, text1 string) ([]byte, error) { text, _ := base64.StdEncoding.DecodeString(string(text1)) block, err := aes.NewCipher(key) if err != nil { return nil, err } if len(text) &lt; aes.BlockSize { return nil, errors.New("ciphertext too short") } iv := text[:aes.BlockSize] text = text[aes.BlockSize:] cfb := cipher.NewCFBDecrypter(block, iv) cfb.XORKeyStream(text, text) b := base64.StdEncoding.EncodeToString(text) data, err := base64.StdEncoding.DecodeString(string(b)) if err != nil { return nil, err } return data, nil } </code></pre> <p>output : ZVnhCXjIvtGKBdqvjwHRZKcVy34=</p> <p>any help would be appreciable.</p> </div>

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,但是数据是不对的,请高手看看为什么调用失败

c#和java aes加密互通的问题

c#段的代码是这样的: public static string AESEncrypt(string EncryptString) { if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(EncryptKey1)) { throw (new Exception("密钥不得为空")); } string m_strEncrypt = ""; byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ=="); Rijndael m_AESProvider = Rijndael.Create(); try { byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString); MemoryStream m_stream = new MemoryStream(); CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey1), m_btIV), CryptoStreamMode.Write); m_csstream.Write(m_btEncryptString, 0, m_btEncryptString.Length); m_csstream.FlushFinalBlock(); m_strEncrypt = Convert.ToBase64String(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_csstream.Close(); m_csstream.Dispose(); } catch (IOException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { m_AESProvider.Clear(); } return m_strEncrypt; } 请问用java怎么实现加密,得到的加密后的结果一致

在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>

JAVA AES ECB加密到Golang迁移

<div class="post-text" itemprop="text"> <p>I try to port a Java implementation of AES decryption to Golang. I need to decrypt data that is previously encrypted by the JAVA code using Golang. But so far I have no luck decrypting it.</p> <p>The Java code is:</p> <pre><code>private static byte[] pad(final String password) { String key; for (key = password; key.length() &lt; 16; key = String.valueOf(key) + key) {} return key.substring(0, 16).getBytes(); } public static String encrypt(String password, String message) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(1, skeySpec); byte[] encrypted = cipher.doFinal(message.getBytes()); return Hex.encodeHexString(encrypted); } public static String decrypt(String password, String message) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(1, skeySpec); cipher.init(2, skeySpec); byte[] original = cipher.doFinal(Hex.decodeHex(message.toCharArray())); return new String(original); } </code></pre> <p>I tried implementations like <a href="https://gist.github.com/JonCooperWorks/5a07d21f930f0c4072d47790b0fe8662" rel="nofollow noreferrer">Cryptography GIST</a> or </p> <pre><code>func decrypt(passphrase, data []byte) []byte { cipher, err := aes.NewCipher([]byte(passphrase)) if err != nil { panic(err) } decrypted := make([]byte, len(data)) size := 16 for bs, be := 0, size; bs &lt; len(data); bs, be = bs+size, be+size { cipher.Decrypt(decrypted[bs:be], data[bs:be]) } return decrypted } hx, _ := hex.DecodeString(hexString) res := decrypt([]byte(password), hx) </code></pre> <p>No error is thrown, and a string is returned. But this string is not anywhere close to the encrypted data. Any help is very much appreciated! Thanks!</p> </div>

在PHP中复制Java的AES / CBC / PKCS5Padding加密

<div class="post-text" itemprop="text"> <p>Have included the java and php code and outputs below. Goal is to get the java checksum value in php. As can be seen I have the same inputs in php as in java and though I have tried a lot of variations of arguments in php's openssl_encrypt function but not able to get the desired output. Help to resolve this will be much appreciated! Do note that the java code is authoritative, any changes needed would be in php only.</p> <p>Java code : </p> <pre><code>import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import java.io.ByteArrayOutputStream; public class ChecksumGen { public static void main(final String[] args) { String data = "INPUTDATA"; String secretKey = "0000000000000000000000000000000000000000000000000000000000000000"; byte[] iv = new byte[16]; try { byte[] hashedData = getDigest(data); byte[] key = hexStringToByteArray(secretKey); byte[] checksum = encrypt(key, hashedData, iv); showB64("key ", key); showB64("iv ", iv); showB64("hashedData ", hashedData); showB64("checksum ", checksum); } catch (Exception ex) { throw new RuntimeException(ex); } } public static byte[] getDigest(String checkSumInput) { try { MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-256"); byte[] checkSumInputBytes = checkSumInput.getBytes("UTF-8"); localMessageDigest.update(checkSumInputBytes); byte[] digest = localMessageDigest.digest(); return digest; } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } public static byte[] hexStringToByteArray(String s) { byte[] b = new byte[s.length() / 2]; for (int i = 0; i &lt; b.length; i++) { int index = i * 2; int v = Integer.parseInt(s.substring(index, index + 2), 16); b[i] = (byte) v; } return b; } public static byte[] encrypt(byte[] key,byte[] data, byte[] iv)throws Exception{ SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); Cipher acipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); acipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivSpec); byte[] arrayOfByte1 = acipher.doFinal(data); return arrayOfByte1; } public static void showB64(String label, byte[] rawData) { System.out.println(label + ":" + Base64.getEncoder().encodeToString(rawData)); } } </code></pre> <p>PHP code :</p> <pre><code>&lt;?php $data = "INPUTDATA"; $hashedData = hash("sha256", $data, true); $secretKey = "0000000000000000000000000000000000000000000000000000000000000000"; $ivStr = "00000000000000000000000000000000"; $key = pack('H*', $secretKey); $iv = pack('H*', $ivStr); $inputData = pkcs5_pad($hashedData, 16); showB64('key', $key); showB64('iv', $iv); showB64('hashedData', $hashedData); showB64('inputData', $inputData); $checksum = encrypt($key, $inputData, $iv); showB64('checksum', $checksum); function encrypt($key,$data,$iv){ $cipher = 'AES-128-CBC'; $options = OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING; $raw = openssl_encrypt( $data, $cipher, $key, $options, $iv ); return $raw; } function pkcs5_pad($text, $blocksize){ $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } function showB64($label, $rawData) { echo "{$label} :".base64_encode($rawData)." "; } </code></pre> <p>Java output :</p> <pre><code>key :AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= iv :AAAAAAAAAAAAAAAAAAAAAA== hashedData :ZAgNCUfIbdT9EjdkCb3XDNpMFGV34rXNjcTOQ9cdZ3w= checksum :9NS/ZKMscpa4V7i2YQQPoycxCwbL1BlK3h9O/1ujoD1iYgjE8tZx+JRGflw5WikH </code></pre> <p>PHP output :</p> <pre><code>key :AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= iv :AAAAAAAAAAAAAAAAAAAAAA== hashedData :ZAgNCUfIbdT9EjdkCb3XDNpMFGV34rXNjcTOQ9cdZ3w= inputData :ZAgNCUfIbdT9EjdkCb3XDNpMFGV34rXNjcTOQ9cdZ3wQEBAQEBAQEBAQEBAQEBAQ checksum :LtdJzSl9UgEpZrpdg7X5g5CYqE3eXQvijazrvkw0XFNY2bxn8zGp1ea8DrUmw/uu </code></pre> </div>

使用AES / CBC / PKCS5Padding进行值加密(PHP代码为Java)

<div class="post-text" itemprop="text"> <p>I have been given sample code in Java and I have to write a code in PHP. Output of PHP Code is not matching with Java Sample Output given. The sample Java code may not be complete (it is what is given in the API documentation given to us. But in essential it summarizes the steps that we need to complete)</p> <p>Message to encrypt is <strong>4NPMCXGERGXSBI7F9IPM5000004NPMCXGERGXSBI7F9IPM</strong></p> <p><strong>JAVA Code</strong> </p> <pre><code>import javax.crypto.Cipher;&lt;/br&gt; import javax.crypto.spec.SecretKeySpec;&lt;/br&gt; import javax.crypto.spec.IvParameterSpec;&lt;/br&gt; import io.fabric.sdk.android.services.network.HttpRequest;&lt;/br&gt; class AAAA{ // class can have any name&lt;/br&gt; public static String getEncryptedTextFor(String text)&lt;/br&gt; throws Exception {&lt;/br&gt; Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");&lt;/br&gt; byte[] keyBytes = new byte[16];&lt;/br&gt; String key = "YASHSHAH!@#987MOBAPP";&lt;/br&gt; byte[] b = key.getBytes("UTF-8");&lt;/br&gt; int len = b.length;&lt;/br&gt; if (len &gt; keyBytes.length) len = keyBytes.length;&lt;/br&gt; System.arraycopy(b, 0, keyBytes, 0, len);&lt;/br&gt; SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");&lt;/br&gt; IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);&lt;/br&gt; cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);&lt;/br&gt; byte[] results = cipher.doFinal(text.getBytes("UTF-8"));&lt;/br&gt; return HttpRequest.Base64.encodeBytes(results);&lt;/br&gt; }&lt;/br&gt; }&lt;/br&gt; </code></pre> <p><strong>PHP Code that we tried</strong> </p> <pre><code> $keyBytes = []; $reqArrLen = 16; $secretKey = 'YASHSHAH!@#987MOBAPP'; $a = utf8_encode($secretKey); $b = unpack('C*', $a); $len = count($b); if($len &gt; $reqArrLen){ $len = $reqArrLen; } foreach ($b as $key =&gt; $value) { if($key &lt;= $len) $keyBytes[]=$value; } echo '&lt;pre&gt;'; $strtobyt = implode(array_map("chr", $keyBytes)); $enLoan_Amount = AesCipher::encrypt($strtobyt, $eLoan_Amount); </code></pre> <p>Sample Output FORMAT in Java is : (This is not the actual output but format is shared) pnehvlPu2gKJXJabR+HbMERdHWnrdc713/SAsHOFWDQ9kv/eWNFI4IRmYWQ6QcoH </p> <pre><code>I'm not able to get this output format after executing PHP code. </code></pre> <p>Sample PHP Output : </p> <p>2438bf468c0142c82127d1dd740f53c3c19125f724265d58811322b50027a876a05b35f61a767fced426597d09f592f3</p> <p>PHP output length is 128 whereas Java is in 64.</p> </div>

android端和java aes加密结果不同

用的org.apache下的commons-codec,android端改了包名导入进去的。 用相同密钥两个平台加密结果不同 代码如下: ![图片说明](https://img-ask.csdn.net/upload/201709/18/1505745042_855033.png) ![图片说明](https://img-ask.csdn.net/upload/201709/18/1505745048_892848.png) ![图片说明](https://img-ask.csdn.net/upload/201709/18/1505745054_210653.png) ![图片说明](https://img-ask.csdn.net/upload/201709/18/1505745058_779693.png)

CryptoJS aes256加密与java aes256加密互通怎么做

CryptoJS aes256加密与java aes256加密互通怎么做,KEY与IV怎么同步比较安全

通过js做出的aes加密与java后台加密出来的不同 求帮助我js 应该修改哪里?

这是java后台的加密 ``` public static String aesEncrypt(String content, String encryptKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom random=SecureRandom.getInstance("SHA1PRNG"); random.setSeed(encryptKey.getBytes()); kgen.init(128, random); SecretKey secretKey = kgen.generateKey(); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptDataByte = cipher.doFinal(content.getBytes("utf-8")); //将二进制转换成16进制 String hexStr = parseByte2HexStr(encryptDataByte); //转换为base64 String encodeStr = Base64.encodeBase64String(hexStr.getBytes()); return encodeStr; } ``` java后台将二进制转换成16进制 ``` /** * 将二进制转换成16进制 * @method parseByte2HexStr * @param buf * @return * @throws * @since v1.0 */ public static String parseByte2HexStr(byte buf[]){ StringBuffer sb = new StringBuffer(); for(int i = 0; i < buf.length; i++){ String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } ``` 这是我用JS写的加密 用的CryptoJS ``` encrypt(word, keyStr) { // 加密 var key = CryptoJS.enc.Utf8.parse(keyStr); var srcs = CryptoJS.enc.Utf8.parse(word) var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }) //console.log("encrypted===" + encrypted.toString()) var base64Str = CryptoJS.enc.Base64.stringify(encrypted.toString()); //转16进制 var dataString = strToHexCharCode(encrypted.toString()); // //base64加密 dataString = window.btoa(dataString.toString()); console.log(dataString); return dataString; }, //转16进制 function strToHexCharCode(str) { if (str === "") return ""; var hexCharCode = []; //hexCharCode.push("0x"); for (var i = 0; i < str.length; i++) { hexCharCode.push((str.charCodeAt(i)).toString(16)); } return hexCharCode.join(""); } ```

Android AES加密后无法解密 求大神指导

package com.example.aes; import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * AES加密解密算法 */ public class AESHelper { /** 算法/模式/填充 **/ private static final String CipherMode = "AES/CBC/PKCS5Padding"; /** 创建密钥 **/ private static SecretKeySpec createKey(String key) { byte[] data = null; if (key == null) { key = ""; } StringBuffer sb = new StringBuffer(16); sb.append(key); while (sb.length() < 16) { sb.append("0"); } if (sb.length() > 16) { sb.setLength(16); } try { data = sb.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return new SecretKeySpec(data, "AES"); } private static IvParameterSpec createIV(String password) { byte[] data = null; if (password == null) { password = ""; } StringBuffer sb = new StringBuffer(16); sb.append(password); while (sb.length() < 16) { sb.append("0"); } if (sb.length() > 16) { sb.setLength(16); } try { data = sb.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return new IvParameterSpec(data); } /** 加密字节数据 **/ public static byte[] encrypt(byte[] content, String password, String iv) { try { SecretKeySpec key = createKey(password); Cipher cipher = Cipher.getInstance(CipherMode); cipher.init(Cipher.ENCRYPT_MODE, key, createIV(iv)); byte[] result = cipher.doFinal(content); return result; } catch (Exception e) { e.printStackTrace(); } return null; } /** 加密(结果为16进制字符串) **/ public static String encrypt(String content, String password, String iv) { byte[] data = null; try { data = content.getBytes("UTF-8"); } catch (Exception e) { e.printStackTrace(); } data = encrypt(data, password, iv); String result = byte2hex(data); return result; } /** 解密字节数组 **/ public static byte[] decrypt(byte[] content, String password, String iv) { try { SecretKeySpec key = createKey(password); Cipher cipher = Cipher.getInstance(CipherMode); cipher.init(Cipher.DECRYPT_MODE, key, createIV(iv)); byte[] result = cipher.doFinal(content); return result; } catch (Exception e) { e.printStackTrace(); } return null; } /** 解密(输出结果为字符串) **/ public static String decrypt(String content, String password, String iv) { byte[] data = null; try { data = hex2byte(content); } catch (Exception e) { e.printStackTrace(); } data = decrypt(data, password, iv); if (data == null) return null; String result = null; try { result = new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } /** 字节数组转成16进制字符串 **/ public static String byte2hex(byte[] b) { // 一个字节的数, StringBuffer sb = new StringBuffer(b.length * 2); String tmp = ""; for (int n = 0; n < b.length; n++) { // 整数转成十六进制表示 tmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (tmp.length() == 1) { sb.append("0"); } sb.append(tmp); } return sb.toString().toUpperCase(); // 转成大写 } /** 将hex字符串转换成字节数组 **/ private static byte[] hex2byte(String inputString) { if (inputString == null || inputString.length() < 2) { return new byte[0]; } inputString = inputString.toLowerCase(); int l = inputString.length() / 2; byte[] result = new byte[l]; for (int i = 0; i < l; ++i) { String tmp = inputString.substring(2 * i, 2 * i + 2); result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF); } return result; } } ------------------------------------------------------------ public class MainActivity extends Activity implements OnClickListener { private Button mJiami, mJiemi; private EditText mName; private String KEY="fe8f95cb0f968676572ab9f46d8a261b"; private String IV ="0F968676572AB9F4"; private String name; String aes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initView(); } private void initView() { mName = (EditText) findViewById(R.id.editText1); name = mName.getText().toString().trim(); mJiami = (Button) findViewById(R.id.button1); mJiemi = (Button) findViewById(R.id.button2); mJiami.setOnClickListener(this); mJiemi.setOnClickListener(this); } @Override public void onClick(View v) { String help = null; switch (v.getId()) { case R.id.button1: try { aes = AESHelper.encrypt(name, KEY, IV); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(this, "加密后值为:"+aes, 0).show(); break; case R.id.button2: try { help = AESHelper.decrypt(aes, KEY, IV); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(help.length()==0){ Toast.makeText(this, "解密失败!", 0).show(); }else{ Toast.makeText(this, help, 0).show(); } break; default: break; } } }

AesEncryption在Java和PHP代码中导致不同的结果,为什么?

<div class="post-text" itemprop="text"> <p>I am connecting a third party interface and they only gave me a Java code demo, I need to connect it with my PHP system.But I can't handle the encryption, my encryption proccess in PHP always gets different result with the third party Java code.</p> <p>I install phpseclib/phpseclib package via composer in order to perform AES encryption.</p> <p>Java Encryption Code:</p> <pre><code>import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; public static String encrypt(String content, String encryptKey) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(encryptKey)); byte[] result = cipher.doFinal(byteContent); return toHexString(result); } catch (Exception ex) { } return null; } private static SecretKeySpec getSecretKey(final String encryptKey) { KeyGenerator kg = null; try { kg = KeyGenerator.getInstance(KEY_ALGORITHM); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(encryptKey.getBytes()); kg.init(128, secureRandom); SecretKey secretKey = kg.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM); } catch (NoSuchAlgorithmException ex) { } return null; } public static String toHexString(byte b[]) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i &lt; b.length; i++) { String plainText = Integer.toHexString(0xff &amp; b[i]); if (plainText.length() &lt; 2) plainText = "0" + plainText; hexString.append(plainText); } return hexString.toString(); } </code></pre> <p>PHP encryption code:</p> <pre><code>//composer require phpseclib/phpseclib use phpseclib\Crypt\AES; function aesEncrypt($message, $key) { $cipher = new AES(AES::MODE_ECB); $cipher-&gt;setKeyLength(128); $cipher-&gt;setKey(hex2bin($key)); $cryptText = $cipher-&gt;encrypt($message); return bin2hex($cryptText); } </code></pre> <p>Java Result:</p> <pre><code>before:testStringtestString key:acccd6fa0caf52a0e5e5fda8bd3ff55a after:2bbd3011eb084c9494228fe913e6e033aaffb1aa04ef9d0f14614c21fd16af9a </code></pre> <p>PHP Result:</p> <pre><code>before:testStringtestString key:acccd6fa0caf52a0e5e5fda8bd3ff55a after:d9a683511cdeb174bf51a285140071a8b38b57c6c6133d1b9425846ae0ec333b </code></pre> </div>

Java:采用Base64编码的AES / CFB / NoPadding加密

<div class="post-text" itemprop="text"> <p>我想使用AES / CFB / NoPadding在Java中加密字节。</p> <p>我在Stackoverflow上发现了以下问题,但它仅涉及解密功能: <a href="https://stackoverflow.com/questions/37210227/aes-encryption-in-golang-and-decryption-in-java">Golang中的AES加密和Java中的解密</a></p> <p>我将如何在Java中编写与以下Go代码类似的加密功能?</p> <pre><code>package main import ( "io" "crypto/aes" "crypto/cipher" "encoding/base64" "crypto/rand" ) func encrypt(key, data []byte) string { block, err := aes.NewCipher(key) if err != nil { return nil, err } encoded := base64.StdEncoding.EncodeToString(data) ciphertext := make( []byte, aes.BlockSize+len(encoded) ) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil, err } cfb := cipher.NewCFBEncrypter(block, iv) cfb.XORKeyStream( ciphertext[aes.BlockSize:], []byte(encoded) ) return ciphertext, nil } </code></pre> <p>我的Golang解密函数如下所示(它应该返回base64代码):</p> <pre><code>func decrypt(key, data []byte) ([]byte, error) { blockcipher, err := aes.NewCipher(key) if err != nil { return nil, err } if len(data) &lt; aes.BlockSize { return nil, errors.New("ciphertext too short") } iv := data[:aes.BlockSize] data = data[aes.BlockSize:] cfb := cipher.NewCFBDecrypter(blockcipher, iv) cfb.XORKeyStream(data, data) return data, nil } </code></pre> <p>我当前的Java加密代码(似乎无法解密)如下所示:</p> <pre><code>private byte[] encrypt(byte[] payload) { try { SecretKeySpec key_spec = new SecretKeySpec(current_encryption_key, "AES"); Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding"); byte[] encoded_payload = Base64.encode(payload, Base64.DEFAULT); IvParameterSpec iv = new IvParameterSpec( new byte[16] ); cipher.init(Cipher.ENCRYPT_MODE, key_spec, iv); return cipher.doFinal(encoded_payload); } catch (Exception e) { e.printStackTrace(); } return new byte[0]; } </code></pre> <p>我的加密代码如下所示(并且在Golang和Java上都可以正常工作):</p> <pre><code>private byte[] decrypt(byte[] payload) { try { SecretKeySpec key_spec = new SecretKeySpec(current_encryption_key, "AES"); Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding"); int block_size = cipher.getBlockSize(); IvParameterSpec iv = new IvParameterSpec( Arrays.copyOf(payload, block_size) ); byte[] decryption_data = Arrays.copyOfRange(payload, block_size, payload.length); cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); byte[] decrypted_payload = cipher.doFinal(decryption_data); return Base64.decode(decrypted_payload, Base64.DEFAULT); } catch (Exception e) { e.printStackTrace(); } return new byte[0]; } </code></pre> <p>当我用Java加密某些内容,然后尝试在Java中使用解密器时,出现了以下解密错误:</p> <pre><code>04-13 14:16:48.382 3791-3791/com.domain.interpretest W/System.err: java.lang.IllegalArgumentException: 16 &gt; 9 04-13 14:16:48.388 3791-3791/com.domain.interpretest W/System.err: at java.util.Arrays.copyOfRange(Arrays.java:3447) </code></pre> </div>

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

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

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

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

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

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

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

和黑客斗争的 6 天!

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

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

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

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

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

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

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

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

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

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

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

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

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

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

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

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

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

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

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

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

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

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

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

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

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

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

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

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

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

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

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

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

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

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

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

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

一文带你入门Java Stream流,太强了

两个星期以前,就有读者强烈要求我写一篇 Java Stream 流的文章,我说市面上不是已经有很多了吗,结果你猜他怎么说:“就想看你写的啊!”你看你看,多么苍白的喜欢啊。那就“勉为其难”写一篇吧,嘻嘻。 单从“Stream”这个单词上来看,它似乎和 java.io 包下的 InputStream 和 OutputStream 有些关系。实际上呢,没毛关系。Java 8 新增的 Stream 是为...

立即提问
相关内容推荐