go java js 对称加密 不同语言可以实现相加密解密的代码实现
时间: 2024-03-08 13:45:50 浏览: 142
是的,对称加密算法可以在不同的编程语言中实现,并且可以实现相同的加密解密结果。下面是一个使用Go、Java和JavaScript实现AES对称加密算法的示例代码:
Go:
```go
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
func main() {
key := []byte("1234567890123456")
plaintext := []byte("Hello, world!")
block, _ := aes.NewCipher(key)
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := rand.Read(iv); err != nil {
panic(err)
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
fmt.Printf("Encrypted: %v\n", base64.URLEncoding.EncodeToString(ciphertext))
}
```
Java:
```java
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws Exception {
byte[] key = "1234567890123456".getBytes();
byte[] plaintext = "Hello, world!".getBytes();
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom(key));
byte[] iv = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));
byte[] ciphertext = cipher.doFinal(plaintext);
System.out.printf("Encrypted: %s\n", Base64.getEncoder().encodeToString(ciphertext));
}
}
```
JavaScript:
```javascript
const crypto = require('crypto');
const key = Buffer.from('1234567890123456');
const plaintext = Buffer.from('Hello, world!');
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
let ciphertext = cipher.update(plaintext);
ciphertext = Buffer.concat([ciphertext, cipher.final()]);
console.log(`Encrypted: ${ciphertext.toString('base64')}`);
```
这三段代码实现了相同的AES对称加密算法,并且输出的加密结果相同。如果需要解密,可以使用相同的密钥和IV值,以及相同的算法和模式进行解密。
阅读全文