我阅读了以下https://nodejs.org/api/crypto.html#crypto_class_sign并尝试复制代码:
签名.js
const crypto = require('crypto');
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1'
});
const sign = crypto.createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');
const verify = crypto.createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true or false
Run Code Online (Sandbox Code Playgroud)
但它给我一个错误
>> node sign.js
internal/crypto/keygen.js:73
throw new ERR_INVALID_OPT_VALUE('publicKeyEncoding', publicKeyEncoding);
^
TypeError [ERR_INVALID_OPT_VALUE]: The value "undefined" is invalid for option "publicKeyEncoding"
at parseKeyEncoding (internal/crypto/keygen.js:73:11)
at check (internal/crypto/keygen.js:240:7)
at Object.generateKeyPairSync (internal/crypto/keygen.js:53:16)
at Object.<anonymous> …Run Code Online (Sandbox Code Playgroud) javascript encryption encryption-asymmetric public-key-encryption node.js
所以我有一个非常基本的 openssl 命令提供给我openssl smime -encrypt -binary -aes-256-cbc -in $inPath -out $encryptedPath -outform DER $pubCert,这个命令也可以正常工作并输出一个加密文件。我需要在 java 应用程序中使用此命令的等效项,最好不要调用进程并使用 openssl 本身(只是因为我觉得这可能是不好的做法)。
我已经研究了很多,似乎没有任何等效的东西可以找到。我尝试了几件事,但大多数似乎都不起作用。奇怪的是......我能够使用我编写的代码获得一个简单的“Hello World”字符串来加密(尽管我不相信它会正确加密它,因为我将密码设置为“RSA”而不是“ AES") 但是当字节数组来自一个文件时,它默默地失败了,只写了 0 个字节。现在这就是我的代码的样子。
Cipher aes = Cipher.getInstance("RSA");
CertificateFactory certF = CertificateFactory.getInstance("X.509");
File public_cert = new File( getClass().getClassLoader().getResource("public.crt").getFile());
FileInputStream certIS = new FileInputStream(public_cert);
X509Certificate cert = (X509Certificate) certF.generateCertificate(certIS);
certIS.close();
aes.init(Cipher.ENCRYPT_MODE, cert);
File tarGz = new File("C:\\volatile\\generic.tar.gz");
FileInputStream fis = new FileInputStream(tarGz);
byte[] tarGzBytes = FileUtils.readFileToByteArray(tarGz);
tarGzBytes = "Hello World".getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream("Hello World".getBytes());
File encFile = …Run Code Online (Sandbox Code Playgroud) 我试图用 JavaScript 加密一个短字符串并用 Java 解密它。解密失败,我认为这是因为两个平台之间的块模式和/或填充不同。我尝试在Java和JavaScript中加密相同的字符串,得到不同的结果,这表明确实存在差异。这是创建密钥的 Java 代码:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.generateKeyPair();
Run Code Online (Sandbox Code Playgroud)
这是我用来测试加密的 Java 代码:
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] bytes = cipher.doFinal("asdf".getBytes());
Run Code Online (Sandbox Code Playgroud)
我将公钥发送到 JavaScript 进程,并将其转换为 ArrayBuffer,变量名为publicKey。我已经验证了 JavaScript 端的密钥与 Java 端的密钥匹配(通过导出它crypto.subtle.exportKey并检查字节)。这是我用来测试加密的 JavaScript 代码:
crypto.subtle.importKey('spki', publicKey,
{hash: 'SHA-256', name: 'RSA-OAEP'}, true,
['encrypt'])
.then((key) => {
crypto.subtle.encrypt({name: 'RSA-OAEP'}, key,
new TextEncoder().encode('asdf'))
.then((buffer) => {
});
});
Run Code Online (Sandbox Code Playgroud)
Java 中的字节数组和 JavaScript 中的数组缓冲区的内容是不一样的。我不确定的设置是Cipher#getInstanceJava 端的参数importKey和encryptJavaScript 端的参数。是否有任何设置可以使用内置类在 Java 和 JavaScript 之间工作?或者我应该查看第三方库(例如,Bouncy …
存储在我的数据库中的密码是这样加密的:
byte[] salt = NewSalt();
string hashedPassword = HashPassword("passwordInTheClear", salt);
// Add/update the admin-user with hashed password and salt.
Run Code Online (Sandbox Code Playgroud)
散列函数:
public static string HashPassword(string password, byte[] salt)
{
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
return Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
}
Run Code Online (Sandbox Code Playgroud)
盐生成器:
public static byte[] NewSalt()
{
// generate a 128-bit salt using a secure PRNG
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create()) …Run Code Online (Sandbox Code Playgroud) 在运行时,在解密密文时,使用 Cipher not initialized 消息获取 java.lang.IllegalStateException 我的代码如下:
public String decrypt(String cipherText) throws SecurityException {
String clearText = null;
try {
cipher = Cipher.getInstance("AES/OFB/NoPadding");
byte[] cipherTextBytes = Base64.decodeBase64(cipherText.getBytes());
byte[] iv = ArrayUtils.subarray(cipherTextBytes, 0, INIT_VECTOR_LENGTH);
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
byte[] decryptedBytes = cipher
.doFinal(ArrayUtils.subarray(cipherTextBytes, INIT_VECTOR_LENGTH, cipherTextBytes.length));
clearText = new String(decryptedBytes, CHARACTER_ENCODING).trim();
} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException
| NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException e) {
throw new SecurityException(e);
}
return clearText;
}
Run Code Online (Sandbox Code Playgroud)
线程“pool-5-thread-3”中的异常java.lang.IllegalStateException:密码未在javax.crypto.Cipher.doFinal(Cipher.java:2156)处的javax.crypto.Cipher.checkCipherState(Cipher.java:1749)处初始化)
这是间歇性问题,一段时间后它解密密文并按预期工作。
java encryption multithreading cryptography illegalstateexception
尝试使用 crypto-js 加密和解密 json 数据。但不工作。如何找到解决方案。如果有人知道,请帮助找到解决方案。
演示:https : //stackblitz.com/edit/angular-ivy-nwhkgz?file=src%2Fapp%2Fapp.component.ts
storageData=
[
{
"customerInfo": {
"Micheal": 1,
"Milson": 2
},
"mycart": {
"Ol1": 1,
"Ol3": 1
},
"cartItemsList": [
{
"pid": "Ol1",
"name": "Avacota",
"qty": 1
},
{
"pid": "Ol3",
"name": "Kaliflower",
"qty": 1
}
],
"cartTotal": 2
}
];
ngOnInit(){
//Encrypt Info
this.encryptInfo = encodeURIComponent(CryptoJS.AES.encrypt(this.storageData, 'secret key 123').toString());
console.log("encryptInfo");
console.log(this.encryptInfo);
//Decrypt Info
var deData= CryptoJS.AES.decrypt(this.encryptInfo, 'secret key 123');
this.decryptedInfo = decodeURIComponent(deData.toString(CryptoJS.enc.Utf8));
console.log("decryptedInfo");
console.log(this.decryptedInfo);
}
Run Code Online (Sandbox Code Playgroud) 我想在 Php 和 Javascript 中加密和解密一些字符串,并在网上查看,最好和最安全的方法似乎是 CryptoJs。
这篇文章不是Encrypt with PHP, Decrypt with Javascript (cryptojs)的副本,因为它的输出字符串并不简单。
这是我的代码,但 Js 解密代码不起作用。怎么了?
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
</head>
<body>
<p>--- PHP ------------------</p>
<?php
function myCrypt($value, $passphrase, $iv){
$encrypted_data = openssl_encrypt($value, 'aes-256-cbc', $passphrase, true, $iv);
return base64_encode($encrypted_data);
}
function myDecrypt($value, $passphrase, $iv){
$value = base64_decode($value);
$data = openssl_decrypt($value, 'aes-256-cbc', $passphrase, true, $iv);
return $data;
}
$valTxt="MyText";
$pswd="MyPassword";
$vector="1234567890123412";
$encrypted = myCrypt($valTxt, $pswd, $vector);
$decrypted = myDecrypt($encrypted, $pswd, $vector);
echo "<p>Text to crypt --------> …Run Code Online (Sandbox Code Playgroud) 当我使用默认的 AES/GCM 算法初始化 Cipher 对象时,它有一个随机的 12 个字节的 IV,但前 4 个字节在调用 doFinal 后不会增加并抛出java.lang.IllegalStateException:无法重新使用相同的密钥和IV 用于多重加密例外。
SecretKey secretKey = ...
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] iv1 = encCipher.getIV();
byte[] ctext = encCipher.doFinal("a".getBytes());
cipher.update("b".getBytes());
byte[] iv2 = encCipher.getIV();
ctext = encCipher.doFinal();
Run Code Online (Sandbox Code Playgroud) 我试图将文本文件的加密内容复制到内存流中,然后解密这些内容并将其复制到新的内存流中。当我到达发生复制的代码时,我在调试时收到无效数据错误。
这是我得到的代码块:
Function DecryptFile(ByVal sInputFilename As String, ByVal sKey As String) As Byte()
Dim DES As New DESCryptoServiceProvider()
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()
Dim encryptedByteArray() As Byte
encryptedByteArray = File.ReadAllBytes(sInputFilename)
Dim encryptedMS As MemoryStream = New MemoryStream(encryptedByteArray)
Dim cryptostreamDecr As New CryptoStream(encryptedMS, desdecrypt, CryptoStreamMode.Read)
Dim decryptedMS As MemoryStream = New MemoryStream()
cryptostreamDecr.CopyTo(decryptedMS) 'Error occurs here
cryptostreamDecr.Close()
Return decryptedMS.ToArray()
End Function
Run Code Online (Sandbox Code Playgroud)
我正在关注散布在网络上的示例,从我读过的内容来看,这段代码应该可以工作......
谁能向我解释我做错了什么?
encryption ×10
java ×4
javascript ×3
cryptojs ×2
aes-gcm ×1
android ×1
angular8 ×1
burp ×1
c# ×1
certificate ×1
cryptography ×1
des ×1
node-crypto ×1
node.js ×1
openssl ×1
php ×1
rsa ×1
security ×1
sha ×1
tripledes ×1
typescript ×1
vb.net ×1