在工作中,难免与其他公司进行合作开发,当遇到不熟悉的语言,需要按照对方的要求进行加密而且没有demo的时候,就比较麻烦。
这个文档主要记录用过的几个加密算法,并且增加不同语言间的对应转换,便于日后参考。
由于很多java代码当时使用线上的环境进行运行和测试的,所以有些inlcude文件没有记录下来,这样在直接使用的时候会造成一些不便,而且使用ruby时间长了以后,很少有引用包、库、头文件的习惯,所以,在运行时,可以根据错误提示,添加相应的包。
AES-128-CBC加密
我常用的语言是ruby,以下是ruby版本加密
具体的内容可参考ruby官方网文档OpenSSL::Cipher
KEY = "08AB199416B82178"
IV = "0102030405060708"
def self.aes_base64_encrypt(message, key, alg = 'AES-128-CBC')
cipher = OpenSSL::Cipher.new(alg)
cipher.encrypt
cipher.key = key
cipher.iv = IV
encrypted = cipher.update(message) + cipher.final
Base64.strict_encode64(encrypted)
end
def self.aes_base64_decrypt(message, key, alg = 'AES-128-CBC')
message = Base64.decode64(message)
decipher = OpenSSL::Cipher.new(alg)
decipher.decrypt
decipher.key = key
decipher.iv = IV
plain = decipher.update(message) + decipher.final
end
然后是对应的java版本的代码
// java
// AES-128-CBC加密的算法java版本找不到了,随后补上
当时找java对应的代码的时候碰巧找到了一个.NET版的,索性也保存了下来
// .NET
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
private const string AesIV = @"0102030405060708";
private const string AesKey = @"08AB199416B82178";
public static void Main()
{
Console.WriteLine("Hello World");
string str1 = Encrypt("hello world");
Console.WriteLine(str1);
string str2 = Decrypt(str1);
Console.WriteLine(str2);
}
public static string Encrypt(string text)
{
// AesCryptoServiceProvider
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 128;
aes.IV = Encoding.UTF8.GetBytes(AesIV);
aes.Key = Encoding.UTF8.GetBytes(AesKey);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
// Convert string to byte array
byte[] src = Encoding.UTF8.GetBytes(text);
// encryption
using (ICryptoTransform encrypt = aes.CreateEncryptor())
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
// Convert byte array to Base64 strings
return Convert.ToBase64String(dest);
}
}
public static string Decrypt(string text)
{
// AesCryptoServiceProvider
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 128;
aes.IV = Encoding.UTF8.GetBytes(AesIV);
aes.Key = Encoding.UTF8.GetBytes(AesKey);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
// Convert Base64 strings to byte array
byte[] src = System.Convert.FromBase64String(text);
// decryption
using (ICryptoTransform decrypt = aes.CreateDecryptor())
{
byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
return Encoding.UTF8.GetString(dest);
}
}
}
AES-128-ECB加密
# ruby
def self.aes_base64_encrypt(message, key, alg = 'AES-128-ECB')
cipher = OpenSSL::Cipher.new(alg)
cipher.encrypt
cipher.key = key
encrypted = cipher.update(message) + cipher.final
Base64.strict_encode64(encrypted)
end
def self.aes_base64_decrypt(message, key, alg = 'AES-128-ECB')
message = Base64.decode64(message)
decipher = OpenSSL::Cipher.new(alg)
decipher.decrypt
decipher.key = key
plain = decipher.update(message) + decipher.final
end
// java
public static byte[] encrypt(byte[] byteS, String pwd) throws Exception {
byte[] byteFina = null;
Cipher cipher;
try {
cipher = Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(getKey(pwd), "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byteFina = cipher.doFinal(byteS);
} catch (Exception e) {
throw e;
} finally {
cipher = null;
}
return byteFina;
}
SHA1加密
#ruby
Digest::SHA1.hexdigest("hello wolrd")
// java
import java.security.*;
import java.io.*;
import java.util.Formatter;
public class HelloWorld{
public static void main(String []args){
String password = "hello world";
String sha1 = "";
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
} catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(sha1);
}
public static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
}
RSA加密 & 公钥签名(SHA256withRSA)
# ruby
require 'openssl'
def self.get_rsa_key(key, key_size = 1024)
if key
rsa = OpenSSL::PKey::RSA.new(key)
else
rsa = OpenSSL::PKey::RSA.new(key_size)
end
[rsa.public_key.to_pem , rsa.to_pem]
end
def self.rsa_private_encrypt(message , rsa_key)
rsa = OpenSSL::PKey::RSA.new(rsa_key)
rsa.private_encrypt(message)
end
def self.rsa_private_decrypt(message , rsa_key)
rsa = OpenSSL::PKey::RSA.new(rsa_key)
rsa.private_decrypt(message)
end
def self.rsa_public_encrypt(message , public_key)
rsa = OpenSSL::PKey::RSA.new(public_key)
rsa.public_encrypt(message)
end
def self.rsa_public_decrypt(message , public_key)
rsa = OpenSSL::PKey::RSA.new(public_key)
rsa.public_decrypt(message)
end
def self.rsa_SHA256_sign(message, rsa_key)
digest = OpenSSL::Digest::SHA256.new
rsa = OpenSSL::PKey::RSA.new(rsa_key)
signature = rsa.sign(digest, message)
if rsa.public_key.verify(digest, signature, message)
signature
else
nil
end
end
// java
public static byte[] encryptData(byte[] source,PublicKey publickey) throws Exception {
Cipher cipher;
byte[]output ;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publickey);
int inputLen = source.length;
int offSet = 0;
int i = 0;
byte[] cache;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(source, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(source, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
output = out.toByteArray();
}
catch(Exception e) {
throw e;
} finally {
out.close();
}
return output;
}
public static byte[] signature(byte[] signedContentStr,PrivateKey privateKey)throws Exception {
Signature sig;
byte[] ret = null ;
sig = Signature.getInstance("SHA256withRSA");
sig.initSign(privateKey);
sig.update(signedContentStr);
ret = (sig.sign());
return ret;
}
网友评论