加密算法

在工作中,难免与其他公司进行合作开发,当遇到不熟悉的语言,需要按照对方的要求进行加密而且没有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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 概述 之前一直对加密相关的算法知之甚少,只知道类似DES、RSA等加密算法能对数据传输进行加密,且各种加密算法各有...
    Henryzhu阅读 3,265评论 0 14
  • 在开发应用过程中,客户端与服务端经常需要进行数据传输,涉及到重要隐私安全信息时,开发者自然会想到对其进行加密,即使...
    闲庭阅读 3,463评论 0 11
  • 这篇文章主要讲述在Mobile BI(移动商务智能)开发过程中,在网络通信、数据存储、登录验证这几个方面涉及的加密...
    雨_树阅读 3,080评论 0 6
  • 在项目开发过程中,当我们利用数据库存储一些关于用户的隐私信息,诸如密码、帐户密钥等数据时,需要加密后才向数据库写入...
    witchiman阅读 2,881评论 0 0
  • 前段时间开发中用到了加密,就趁这个机会查阅了一些相关的资料,对解密加深了一些印象,以下是我的一些总结。 消息摘要算...
    肚子总是饿阅读 3,484评论 0 21

友情链接更多精彩内容