GVKun编程网logo

如何使用Rijndael和256位的块大小进行加密或解密?

18

在本文中,我们将详细介绍如何使用Rijndael和256位的块大小进行加密或解密?的各个方面,同时,我们也将为您带来关于Android:使用iv和密钥通过AES256位加密对字符串进行加密、asp-c

在本文中,我们将详细介绍如何使用Rijndael和256位的块大小进行加密或解密?的各个方面,同时,我们也将为您带来关于Android:使用iv和密钥通过AES 256位加密对字符串进行加密、asp-classic – 如何使用AES在VBScript中进行加密?、c# – 使用Rijndael加密/解密文件、c# – 如何使用AES(Rijndael)检查文件是否加密的有用知识。

本文目录一览:

如何使用Rijndael和256位的块大小进行加密或解密?

如何使用Rijndael和256位的块大小进行加密或解密?

出于某些原因,我需要使用256位的块大小而不是使用128位块大小的AES来实现Rijndael de /
compression(原因:数据使用Rijndael在PHP中加密)。

如何更改密码的块大小?

如果我只是使用cipher "RIJNDAEL/CFB/PKCS5Padding"并尝试使用256位初始化IV,则会出现异常,因为块大小仅为128位。

答案1

小编典典

除了具有128位块大小的Rijndael之外,任何Sun
JCE提供程序都不支持任何其他功能:这是AES算法。要获得具有256位块大小的rijndael,您将不得不走到其他地方。我建议Bouncycastle
Java库。该RijndaelEngine类有接受位的块大小的构造函数。大多数人都发现,与适当的填充一起使用时,PaddedBufferedBlockCipher类更方便,例如

PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new RijndaelEngine(256), new PKCS7Padding());

Android:使用iv和密钥通过AES 256位加密对字符串进行加密

Android:使用iv和密钥通过AES 256位加密对字符串进行加密

SecureRandom random = new SecureRandom(); // quite heavy, look into a lighter method.String stringToEncrypt = "mypassword";byte[] realiv = new byte[16];random.nextBytes(realiv);Cipher ecipher = Cipher.getInstance("AES");SecureRandom random = new SecureRandom(); // quite heavy, look into a lighter method.byte[] realiv = new byte[16];random.nextBytes(realiv);byte[] secret = "somelongsecretkey".getBytes();SecretKeySpec secretKey = new SecretKeySpec(secret, "AES");ecipher.init(Cipher.ENCRYPT_MODE, secretKey, random);byte[] encryptedData = ecipher.doFinal();

init()只有3个参数。我需要一种方法来做这样的事情:

ecipher.init(Cipher.ENCRYPT_MODE, stringToEncrypt, secretKey, random);

答案1

小编典典

通常,您不需要为具有确定性行为的算法生成随机数的对象。此外,在使用ECB块模式时,您不需要IV,这是Java默认设置。确切地说,Java默认为中的"AES/ECB/PKCS5Padding"for
Cipher.getInstance("AES")

因此,您应该可以使用如下代码:

// lets use the actual key value instead of the platform specific character decodingbyte[] secret = Hex.decodeHex("25d6c7fe35b9979a161f2136cd13b0ff".toCharArray());// that''s fineSecretKeySpec secretKey = new SecretKeySpec(secret, "AES");// SecureRandom should either be slow or be implemented in hardwareSecureRandom random = new SecureRandom();// first create the cipherCipher eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// filled with 00h characters first, use Cipher instance so you can switch algorithmsbyte[] realIV = new byte[eCipher.getBlockSize()];// actually fill with randomrandom.nextBytes(realIV);// MISSING: create IvParameterSpecIvParameterSpec ivSpec = new IvParameterSpec(realIV);// create the cipher using the IVeCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);// NOTE: you should really not encrypt passwords for verificationString stringToEncrypt = "mypassword";// convert to bytes first, but don''t use the platform encodingbyte[] dataToEncrypt = stringToEncrypt.getBytes(Charset.forName("UTF-8"));// actually do the encryption using the databyte[] encryptedData = eCipher.doFinal(dataToEncrypt);

现在看起来好多了。我已使用Apache Commons编解码器解码十六进制字符串。

请注意,您需要保存realIVencryptedData和你有没有包括完整性保护,如MAC(口令,你可能不需要,虽然)。

asp-classic – 如何使用AES在VBScript中进行加密?

asp-classic – 如何使用AES在VBScript中进行加密?

我正在使用 VBScript中的 Rijndael/AES使用特定的键和 IV值加密一些数据.有没有什么好的函数库或COM组件可以很好的使用?

我看着CAPICOM;它只允许一个密码短语,并且不允许设置特定的键和IV值.

解决方法

一个响应建议将RijndaelManaged类包装在COM中.您还可以在COM中包装其他AES实现.我刚刚尝试了 SlowAES,这是AES的JavaScript实现.通过Windows脚本组件将其包装在COM中可以从VBScript调用.我只会在不能使用.NET方法时推荐这个;我猜想AES的.NET将比在JavaScript中实现的AES更快.

在我对COM-wrapped-SlowAEs的测试中,我使用CBC模式,加密与.NET中的RijndaelManaged类完全兼容.

这是WSC;我省略了SlowAES提供的3个.js文件.您需要在我标记文件时不变地插入它们.

<?xml version="1.0"?>

<!--

//
// Ionic.COM.SlowAES.wsc
//
// This is a Windows Script Component that exposes the SlowAES
// encryption engine via COM. This AES can be used from any 
// COM-capable environment,including Javascript or VBScript. 
//
//
// This code is licensed under the Microsoft Public License. See the
// accompanying License.txt file for details.
//
// copyright 2009 Dino Chiesa
//

-->

<package>

<component id="Ionic.Com.SlowAES">

  <comment>
SlowAES is a Javascript implementation of AES.  
     See http://code.google.com/p/slowaes.  
This is a COM package for SlowAES.
  </comment>

<?component error="true" debug="true"?>

<registration
  description="WSC Component for SlowAES"
  progid="Ionic.Com.SlowAES"
  version="1.00"
  classid="{ba78383f-1bcc-4df6-9fb9-61cd639ebc94}"
  remotable="False">

  <!-- boilerplate registration/unregistration logic -->
  <script language="VBScript">
  <![CDATA[

strComponent = "Ionic SlowAES"

Function Register
  MsgBox strComponent & " - registered."
End Function

Function Unregister
  MsgBox strComponent & " - unregistered."
End Function

  ]]>
  </script>
</registration>

<public>
  <method name="EncryptString">
<parameter name="plainText"/>
  </method>

  <method name="DecryptBytes">
<parameter name="cipherText"/>
  </method>

  <method name="DecryptBytesToString">
<parameter name="cipherText"/>
  </method>

  <method name="DecryptHexString">
<parameter name="hexStringCipherText"/>
  </method>

  <method name="DecryptCommaDelimitedStringToString">
<parameter name="cipherText"/>
  </method>

  <property name="Key">
  <put/>
  </property>

  <property name="Mode">
  <put/>
  <get/>
  </property>

  <property name="IV">
  <put/>
  <get/>
  </property>

  <property name="KeySize">
  <put/>
  <get/>
  </property>
</public>

<script language="JavaScript">
<![CDATA[

// ...insert slowAES code here... //

// defaults
var _keysize = slowAES.aes.SIZE_128;
var _mode = slowAES.modeOfOperation.CBC;
var _iv = [0,0];
var _key;

/* 
* byteArrayToHexString
* convert a byte array to hex string.
*/
function byteArrayToHexString(a)
{
try { hexcase } catch(e) { hexcase=0; }
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var r= "";
for (var i = 0; i < a.length; i++)
{
    var b  = hex_tab.charat((a[i] >> 4) & 0x0F) + 
    hex_tab.charat(a[i] & 0x0F);
    r+= b;
}
return r;
}

/* 
* hexStringToByteArray
* convert a string of hex byts to a byte array
*/
function hexStringToByteArray(s)
{
var r= Array(s.length/2);
for (var i = 0; i < s.length; i+=2)
{
    r[i/2] = parseInt(s.substr(i,2),16);
}
return r;
}

function EncryptString(plainText)
{
 var bytesToEncrypt = cryptoHelpers.convertStringToByteArray(plainText);
 var result = slowAES.encrypt(bytesToEncrypt,_mode,_key,_keysize,_iv);
return result['cipher'];
}

function DecryptBytesToString(cipherText)
{
var d = DecryptBytes(cipherText);
var s = cryptoHelpers.convertByteArrayToString(d);
s[cipherText.length]= 0;
return s;
}

function DecryptHexString(hexStringCipherText)
{
var cipherText = hexStringToByteArray(hexStringCipherText);
return DecryptBytesToString(cipherText);
}

function DecryptCommaDelimitedStringToString(cipherText)
{
var c = [];
var atoms = cipherText.split(",");
for (i=0; i < atoms.length; i++)
{
    c.push(parseInt(atoms[i],10));
}
var d = DecryptBytes(c);
return cryptoHelpers.convertByteArrayToString(d);
}

function DecryptBytes(cipherText)
{
if (cipherText == undefined) return null;

var originalSize = cipherText.length;

var result = slowAES.decrypt(cipherText,originalSize,_iv);

return result;
}

function put_Key(keyString)
{
  _key = hexStringToByteArray(keyString);
}

function put_KeySize(size)
{
if (size == 128) _keysize = slowAES.aes.keySize.SIZE_128;
else if (size == 192) _keysize = slowAES.aes.keySize.SIZE_192;
else if (size == 256) _keysize = slowAES.aes.keySize.SIZE_256;
else
    throw "Unsupported key size.  Must be one of { 128,192,256 }.";
}

function get_KeySize()
{
if (_keysize == slowAES.aes.keySize.SIZE_128) return 128;
else if (_keysize == slowAES.aes.keySize.SIZE_192) return 192;
else if (_keysize == slowAES.aes.keySize.SIZE_256) return 256;
else return -1;
}

function put_IV(ivString)
{
    _iv = hexStringToByteArray(ivString);
}

function get_IV()
{
return byteArrayToHexString(_iv);
}

function put_Mode(mode)
{
if (mode == "CBC") _mode= slowAES.modeOfOperation.CBC;
else if (mode == "OFB") _mode= slowAES.modeOfOperation.OFB;
else if (mode == "CFB") _mode= slowAES.modeOfOperation.CFB;
else throw "Unsupported mode.  Must be one of {CBC,OFB,CFB}";
}

function get_Mode()
{
if (_mode == slowAES.modeOfOperation.CBC) return "CBC";
if (_mode == slowAES.modeOfOperation.OFB) return "OFB";
if (_mode == slowAES.modeOfOperation.CFB) return "CFB";
return "???";
}

]]>

</script>

</component>

</package>

保存到一个名为SlowAES.wsc的文件.注册“regsvr32 SlowAES.wsc”.
这是一些使用该组件的VBScript代码.

' '
' byteArrayToHexString'
' convert a byte array to hex string.'
' '
Function byteArrayToHexString(a)
Dim r,b,i
r = ""
For i = 0 To UBound(a)
    b = Hex( (a(i) And &HF0) / 16) & Hex(a(i) And &HF)
    r= r & b
Next
byteArrayToHexString= r
End Function

' '
' hexStringToByteArray'
' convert a string of hex byts to a byte array'
' '
Function hexStringToByteArray(s)
Dim r()
ReDim r(Len(s)/2-1)
Dim x
For i = 0 To  Len(s)-2 Step 2
    x= "&H" & Mid(s,i+1,2)
    r(i/2) = CInt(x)
Next
hexStringToByteArray= r
End Function

Function DemoEncryption()
WScript.echo "Testing Ionic.Com.SlowAES..."

WScript.echo "key:              " & byteArrayToHexString(key)
WScript.echo "iv:               " & byteArrayToHexString(iv)
WScript.echo "key length:       " & keyLengthInBytes & " bytes"
WScript.echo "key length:       " & (keyLengthInBytes*8) & " bits"
WScript.echo "plaintext:        " & plaintext
WScript.echo "plaintext.length: " & Len(plaintext)

WScript.echo "instantiate Ionic.Com.SlowAES"
Dim aes
set aes = CreateObject("Ionic.Com.SlowAES")

WScript.echo "keysize"
aes.KeySize = keyLengthInBytes * 8

WScript.echo "key"
aes.Key = byteArrayToHexString(key)

WScript.echo "iv "
aes.IV= byteArrayToHexString(iv)

WScript.echo "mode "
aes.Mode = "CBC"

WScript.echo "encrypting... "
Dim result
result= aes.EncryptString(plaintext)

' result is a comma-separated string '
' if we Eval() on it we convert it to an array '
Dim expr
expr = "Array(" & result & ")" 

result= Eval( expr )

WScript.echo "Cryptotext/Eval: " & byteArrayToHexString(result)
WScript.echo "Cryptotext.length: " & UBound(result)+1

WScript.echo "decrypting... "
Dim decrypted
'The javascript way to do this is to pass the byte array.'
' Like so:'
'    var decrypted = aes.DecryptBytesToString(result);'
' '
'This does not work from VBScript. So,convert to a hexstring,'
'pass the hex string,and then convert back,in the COM component.'
decrypted= aes.DecryptHexString(byteArrayToHexString(result))

WScript.echo "decrypted: " & decrypted
End Function

dim plaintext,iv,key,keyLengthInBytes

plaintext= "Hello. This is a test. of the emergency broadcasting system."
' iv must be a hexstring representation of an array of bytes,length=16'
iv =  hexStringToByteArray("FeedbeefFeedbeefbaadf00dbaadf00d")
' key must be a hexstring representation of an array of bytes,length=16 or 32'
key = hexStringToByteArray("cafebabe0099887766554433221100AA")
keyLengthInBytes= UBound(key)+1

If Err.Number <> 0 Then Err.Clear

Call DemoEncryption

If (Err.Number <> 0) Then WScript.echo("Error: " & Err.Description)

如果您还需要基于密码的密钥导出功能,那么可以抓取the very succint JavaScript code for PBKDF2 here和create another WSC for that,而不会有太多麻烦.

编辑:我做了我所描述的 – 抓住了PBKDF2的源码,并将其整合到了SlowAES的代码中.我还在C#中生成了第二个独立的实现,它使用内置的.NET类库来执行RFC 2898密钥派生和AES加密.

结果是3个测试应用程序,一个在C#中,一个在JavaScript中,另一个在VBScript中.他们都采取同样的论据.它们各自使用符合RFC 2898标准的密钥导出功能.您可以指定密码,salt,IV和明文,以及在PBKDF2中使用的RFC 2898迭代次数.您可以轻松地验证每个测试程序的密文是否相同.也许这个例子对于某人是有用的.

c# – 使用Rijndael加密/解密文件

c# – 使用Rijndael加密/解密文件

我需要传输xml文件,并且需要加密它们.我发现一些例子认为我很接近,但是当我解密文件时,我最终会遇到尾随垃圾字符.有一些关于这个的帖子,但我没有看到任何将完全有帮助.这是加密和解密代码.
private void EncryptFile(string inputFile,string outputFile,string key) {
    try {
        byte[] keyBytes;
        keyBytes = Encoding.Unicode.GetBytes(key);

        Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(key,keyBytes);

        RijndaelManaged rijndaelCSP = new RijndaelManaged();
        rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
        rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);

        ICryptoTransform encryptor = rijndaelCSP.CreateEncryptor();

        FileStream inputFileStream = new FileStream(inputFile,FileMode.Open,FileAccess.Read);

        byte[] inputFileData = new byte[(int)inputFileStream.Length];
        inputFileStream.Read(inputFileData,(int)inputFileStream.Length);

        FileStream outputFileStream = new FileStream(outputFile,FileMode.Create,FileAccess.Write);

        CryptoStream encryptStream = new CryptoStream(outputFileStream,encryptor,CryptoStreamMode.Write);
        encryptStream.Write(inputFileData,(int)inputFileStream.Length);
        encryptStream.FlushFinalBlock();

        rijndaelCSP.Clear();
        encryptStream.Close();
        inputFileStream.Close();
        outputFileStream.Close();
    }
    catch (Exception ex) {
        MessageBox.Show(ex.Message,"Encryption Failed!",MessageBoxButtons.OK,MessageBoxIcon.Error);
        return;
    }

    MessageBox.Show("File Encryption Complete!");

}

private void DecryptFile(string inputFile,string key) {
    try {
        byte[] keyBytes = Encoding.Unicode.GetBytes(key);

        Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(key,keyBytes);

        RijndaelManaged rijndaelCSP = new RijndaelManaged();
        rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
        rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
        ICryptoTransform decryptor = rijndaelCSP.CreateDecryptor();

        FileStream inputFileStream = new FileStream(inputFile,FileAccess.Read);

        CryptoStream decryptStream = new CryptoStream(inputFileStream,decryptor,CryptoStreamMode.Read);

        byte[] inputFileData = new byte[(int)inputFileStream.Length];
        decryptStream.Read(inputFileData,FileAccess.Write);
        outputFileStream.Write(inputFileData,inputFileData.Length);
        outputFileStream.Flush();

        rijndaelCSP.Clear();

        decryptStream.Close();
        inputFileStream.Close();
        outputFileStream.Close();
    }
    catch (Exception ex) {
        MessageBox.Show(ex.Message,"Decryption Failed!",MessageBoxIcon.Error);
        return;
    }

    MessageBox.Show("File Decryption Complete!");
}

我结束了

<?xml version="1.0" encoding="UTF-8"?>
<transaction>
  <header>
    <qOrderNumber></qOrderNumber>
    <qRequestDate></qRequestDate>
    <testOrder></testOrder>
    <qCustomerNumber></qCustomerNumber>
    <transactionStatus></transactionStatus>
  </header>
  <lines>
    <line>
      <productID></productID>
      <serialNumber></serialNumber>
    </line>
    <line> 
      <productID></productID>
      <serialNumber></serialNumber>
    </line>
  </lines>
</transaction>NULNULNULNULNULNUL

解决方法

解密时,请注意CryptoStream.Read调用的返回值.它告诉您字节数组中解密数据的长度(通常与填充引起的加密数据长度不匹配).尝试在解密函数中使用以下内容:
int decrypt_length = decryptStream.Read(inputFileData,(int)inputFileStream.Length);
FileStream outputFileStream = new FileStream(outputFile,FileAccess.Write);
outputFileStream.Write(inputFileData,decrypt_length);

c# – 如何使用AES(Rijndael)检查文件是否加密

c# – 如何使用AES(Rijndael)检查文件是否加密

我在C#中使用’RijndaelManaged’和’CryptoStream’类来加密文件.在加密文件之前,我想检查文件是否已加密.

我尝试使用File.GetAttributes()方法来检查加密,但它无法正常工作.

我需要一些提示,我可以检查文件是否已加密.

解决方法

没有任何类型的自定义标头,绝对确保文件加密的唯一方法是尝试解密它.

如果您尝试压缩文件并且文件变小,则极不可能加密.如果字节值的分布不均匀(包括纯文本!),则不太可能加密.

这些启发式方法取决于加密的正确执行.如果AES一次应用于一个文件块,那么可以在结果中出现模式,但由于您使用的是CryptoStream,因此这不应该是一个问题.

如果您自己的代码将始终用于加密和解密文件,那么您应该考虑添加一个自定义标头,指示它是加密文件.

我们今天的关于如何使用Rijndael和256位的块大小进行加密或解密?的分享就到这里,谢谢您的阅读,如果想了解更多关于Android:使用iv和密钥通过AES 256位加密对字符串进行加密、asp-classic – 如何使用AES在VBScript中进行加密?、c# – 使用Rijndael加密/解密文件、c# – 如何使用AES(Rijndael)检查文件是否加密的相关信息,可以在本站进行搜索。

本文标签: