原文:http://outofmemory.cn/code-snippet/35524/AES-with-javascript-java-csharp-python-or-php
c#裡面的AES加密解密
在visual studio中寫的c#代碼
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Security.Cryptography;namespacetest
{classClass1
{static void Main(string[] args)
{
Console.WriteLine("I am comming");
String source= "Test String";
String encryptData= Class1.Encrypt(source, "1234567812345678", "1234567812345678");
Console.WriteLine("=1==");
Console.WriteLine(encryptData);
Console.WriteLine("=2==");
String decryptData= Class1.Decrypt("2fbwW9+8vPId2/foafZq6Q==", "1234567812345678", "1234567812345678");
Console.WriteLine(decryptData);
Console.WriteLine("=3==");
Console.WriteLine("I will go out");
}public static string Encrypt(string toEncrypt, string key, stringiv)
{byte[] keyArray =UTF8Encoding.UTF8.GetBytes(key);byte[] ivArray =UTF8Encoding.UTF8.GetBytes(iv);byte[] toEncryptArray =UTF8Encoding.UTF8.GetBytes(toEncrypt);
RijndaelManaged rDel= newRijndaelManaged();
rDel.Key=keyArray;
rDel.IV=ivArray;
rDel.Mode=CipherMode.CBC;
rDel.Padding=PaddingMode.Zeros;
ICryptoTransform cTransform=rDel.CreateEncryptor();byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}public static string Decrypt(string toDecrypt, string key, stringiv)
{byte[] keyArray =UTF8Encoding.UTF8.GetBytes(key);byte[] ivArray =UTF8Encoding.UTF8.GetBytes(iv);byte[] toEncryptArray =Convert.FromBase64String(toDecrypt);
RijndaelManaged rDel= newRijndaelManaged();
rDel.Key=keyArray;
rDel.IV=ivArray;
rDel.Mode=CipherMode.CBC;
rDel.Padding=PaddingMode.Zeros;
ICryptoTransform cTransform=rDel.CreateDecryptor();byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);returnUTF8Encoding.UTF8.GetString(resultArray);
}
}
}
其中加密後以及解密後的字元串都能成功列印,但Console.WriteLine("=3==");之後的輸出就沒有了,最後輸出個線程傳回值0,然後就沒有然後了。c#不懂,就不深究了,就已執行的部分,是符合要求了。
Java的AES加密解密:
java代碼,測試也是可以的
importjavax.crypto.Cipher;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importorg.junit.Test;
...
@Testpublic void testCrossLanguageEncrypt() throwsException{
System.out.println(encrypt());
System.out.println(desEncrypt());
}public static String encrypt() throwsException {try{
String data= "Test String";
String key= "1234567812345678";
String iv= "1234567812345678";
Cipher cipher= Cipher.getInstance("AES/CBC/NoPadding");int blockSize =cipher.getBlockSize();byte[] dataBytes =data.getBytes();int plaintextLength =dataBytes.length;if (plaintextLength % blockSize != 0) {
plaintextLength= plaintextLength + (blockSize - (plaintextLength %blockSize));
}byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes,0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec= new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec= newIvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);byte[] encrypted =cipher.doFinal(plaintext);return newsun.misc.BASE64Encoder().encode(encrypted);
}catch(Exception e) {
e.printStackTrace();return null;
}
}public static String desEncrypt() throwsException {try{
String data= "2fbwW9+8vPId2/foafZq6Q==";
String key= "1234567812345678";
String iv= "1234567812345678";byte[] encrypted1 = newsun.misc.BASE64Decoder().decodeBuffer(data);
Cipher cipher= Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec= new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec= newIvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);byte[] original =cipher.doFinal(encrypted1);
String originalString= newString(original);returnoriginalString;
}catch(Exception e) {
e.printStackTrace();return null;
}
}
php的AES加密解密
php代碼,php很多東西都是提供好的,直接用函數,但是php目前所知填充模式隻有ZeroPadding,于是其他語言就隻能跟着它來了:
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);echo($encrypted);echo '
';echo(base64_encode($encrypted));echo '
';//解密
$encryptedData = base64_decode("2fbwW9+8vPId2/foafZq6Q==");$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $encryptedData, MCRYPT_MODE_CBC, $iv);echo($decrypted);?>
Javascript下aes加解密,試過也可以,需要在https://code.google.com/p/crypto-js/下載下傳工具包
導入檔案,aes.js需要導入crypto-js壓縮包中rollups檔案夾下的那個aes.js檔案,如果引入的是components檔案夾下的aes.js是會報錯的
var data = "Test String";var key = CryptoJS.enc.Latin1.parse('1234567812345678');var iv = CryptoJS.enc.Latin1.parse('1234567812345678');//加密
var encrypted =CryptoJS.AES.encrypt(data,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding});
document.write(encrypted.ciphertext);
document.write('
');
document.write(encrypted.key);
document.write('
');
document.write(encrypted.iv);
document.write('
');
document.write(encrypted.salt);
document.write('
');
document.write(encrypted);
document.write('
');//解密
var decrypted =CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
console.log(decrypted.toString(CryptoJS.enc.Utf8));
成功加解密,最後解密的字元串串在浏覽器的控制台裡才能看到。
python的AES加密解密
最後加一個python下的aes,需要安裝python Crypto:
#!/usr/bin/env python#-*- coding: utf-8 -*-
from Crypto.Cipher importAESimportbase64
PADDING= '\0'
#PADDING = ' '
pad_it = lambda s: s+(16 - len(s)%16)*PADDING
key= '1234567812345678'iv= '1234567812345678'source= 'Test String'generator=AES.new(key, AES.MODE_CBC, iv)
crypt=generator.encrypt(pad_it(source))
cryptedStr=base64.b64encode(crypt)printcryptedStr
generator=AES.new(key, AES.MODE_CBC, iv)
recovery=generator.decrypt(crypt)print recovery.rstrip(PADDING)
注意python下需要用'\0'來填充,如果是空格來填充,python加密得到的字元串會跟其他語言不同。另外注意generator在加密的時候使用過,解密的時候需重新生成再解密,否則解密失敗。最後得到的字元串,在python控制台看到尾部是多個NUL這樣的東西,要這樣recovery.rstrip(PADDING)去除掉才是原始字元串。
可以看到aes加密的中間結果是byte[]類型,直接new String(byte[])會看不到有意義的中間結果,這裡用的是base64,是因為各個語言都有這樣的支援。在同個語言内,也有bytesToHexString這樣的方式。
跨語言加解密的要求是:AES/CBC/ZeroPadding 128位模式,key和iv一樣,編碼統一用utf-8。不支援ZeroPadding的就用NoPadding.