.NET中的Java等效加密代码(rsa/ecb/pkcs1padding C#) [英] Java equivalent encryption code in .NET (rsa/ecb/pkcs1padding c#)
问题描述
包com.axis.security;
导入java.security.PrivateKey;
导入java.security.Provider;
导入java.security.PublicKey;
导入java.security.Security;
导入java.security.Signature;
导入java.security.spec.KeySpec;
导入javax.crypto.Cipher;
导入javax.crypto.SecretKey;
导入javax.crypto.SecretKeyFactory;
导入javax.crypto.spec.IvParameterSpec;
导入javax.crypto.spec.PBEKeySpec;
导入javax.crypto.spec.SecretKeySpec;
导入org.bouncycastle.jce.provider.BouncyCastleProvider;
公共类SGSecuror
{
公共静态最终字节[] iv_as_AllZEROS = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
静态{
提供者p = Security.getProvider("BC");
if(p == null){
Security.addProvider(new BouncyCastleProvider());
}
}
公共静态boolean verifyDataRSA(byte [] data,byte [] singature,PublicKey publicKey)引发异常
{
if(data == null){
引发新的Exception(数据为空");
}
if(data.length == 0){
引发新的Exception(数据长度为零");
}
if(singature == null){
引发新的Exception("Signature is empty");
}
if(singature.length == 0){
引发新的Exception(签名长度为零");
}
if(publicKey == null){
引发新的异常(证书公钥为空");
}
if(publicKey.getAlgorithm().compareTo("RSA")!= 0){
引发新的异常(证书算法不是RSA");
}
试试
{
签名sig = Signature.getInstance("SHA1WithRSA","BC");
sig.initVerify(publicKey);
sig.update(data);
返回sig.verify(singature);
}
catch(特例例外){
扔前;
}
}
公共静态字节[]解密RSA(字节[]加密,专用密钥专用密钥)引发异常
{
if(encrypted == null){
引发新的Exception(数据为空");
}
if(encrypted.length == 0){
引发新的Exception(数据长度为零");
}
if(privateKey == null){
引发新的异常(证书私钥为空");
}
if(privateKey.getAlgorithm().compareTo("RSA")!= 0){
引发新的异常(证书算法不是RSA");
}
尝试{
byte [] encryptionByte = null;
密码cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(2,privateKey);
byte [] someDecrypted = cipher.update(encrypted);
byte [] moreDecrypted = cipher.doFinal();
byte []解密=新的byte [someDecrypted.length + moreDecrypted.length];
System.arraycopy(someDecrypted,0,decrypted,0,someDecrypted.length);
System.arraycopy(moreDecrypted,0,解密,someDecrypted.length,moreDecrypted.length);
返回已解密;
}
catch(特例例外){
扔前;
}
}
公共静态字节[] signDataRSA(字节[]数据,私钥privateKey)引发异常{
if(data == null){
引发新的Exception(数据为空");
}
if(data.length == 0){
引发新的Exception(数据长度为零");
}
if(privateKey == null){
引发新的异常(证书私钥为空");
}
if(privateKey.getAlgorithm().compareTo("RSA")!= 0){
引发新的异常(证书算法不是RSA");
}
试试
{
签名签名= Signature.getInstance("SHA1WithRSA","BC");
signature.initSign(privateKey);
signature.update(data);
返回signature.sign();
}
catch(特例例外){
扔前;
}
}
公共静态字节[] cryptoRSA(字节[] plainData,公共密钥pubKey)引发异常{
if(plainData == null){
引发新的Exception(数据为空");
}
如果(plainData.length == 0){
引发新的Exception(数据长度为零");
}
if(pubKey == null){
引发新的异常(证书公钥为空");
}
if(pubKey.getAlgorithm().compareTo("RSA")!= 0){
引发新的异常(证书算法不是RSA");
}
试试
{
byte [] encryptionByte = null;
密码cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(1,pubKey);
byte [] someData = cipher.update(plainData);
byte [] moreData = cipher.doFinal();
byte []加密=新的byte [someData.length + moreData.length];
System.arraycopy(someData,0,加密,0,someData.length);
System.arraycopy(moreData,0,加密,someData.length,moreData.length);
返回加密的;
}
catch(特例例外){
扔前;
}
}
公共静态字节[]解密AES(字节[]密钥,字节[]加密,字节[] iv)
引发异常
{
if(key == null){
引发新的Exception("Key is empty");
}
if(((key.length!= 16)&&(key.length!= 24)&&(key.length!= 32)){
抛出新的异常(密钥长度无效.只能为16,24或32.");
}
如果(iv == null){
引发新的异常("IV为空");
}
if(encrypted == null){
引发新的Exception(数据为空");
}
试试
{
SecretKeySpec skeySpec =新的SecretKeySpec(key,"AES");
密码cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivspec =新的IvParameterSpec(iv);
cipher.init(2,skeySpec,ivspec);
返回cipher.doFinal(已加密);
}
catch(异常e){
抛出e;
}
}
公共静态字节[] generateKeyAESKey(字符[]密码,字节[] iv,int迭代计数,int keyLength)引发异常
{
if(密码==空){
引发新的Exception("Password is empty");
}
if(password.length == 0){
引发新的Exception(密码长度为零");
}
如果(iv == null){
引发新的异常("IV为空");
}
如果(iv.length == 0){
引发新的Exception("IV的长度为零");
}
if(iterationCount< 1000){
引发新异常(迭代计数应小于1000");
}
if(((keyLength!= 128)&&(; keyLength!= 192)&&(keyLength!= 256)){
抛出新的异常(密钥长度无效.它只能是128或192或256.");
}
试试
{
KeySpec keySpec =新的PBEKeySpec(密码,iv,iterationCount,keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte [] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey skey =新的SecretKeySpec(keyBytes,"AES");
返回skey.getEncoded();
}
catch(异常e)
{
抛出e;
}
}
公共静态字节[] cryptoAES(字节[]密钥,字节[]清除,字节[] iv)引发异常
{
if(key == null){
引发新的Exception("Key is empty");
}
if((key.length!= 16)&&(key.length!= 24)&&(key.length!= 32)){
抛出新的异常(密钥长度无效.只能为16,24或32.");
}
如果(iv == null){
引发新的异常("IV为空");
}
if(clear == null){
引发新的Exception(数据为空");
}
试试
{
SecretKeySpec skeySpec =新的SecretKeySpec(key,"AES");
密码cipher = Cipher.getInstance("AES/CBC/PKCS5Padding","BC");
IvParameterSpec ivspec =新的IvParameterSpec(iv);
cipher.init(1,skeySpec,ivspec);
返回cipher.doFinal(clear);
}
catch(异常e){
抛出e;
}
}
公共SGSecuror(){}
}
Hi 与 java 的加密
{
公共类SGSecuror
{
公开SGSecuror()
{
//提供商p = Security.getProvider("BC");
//如果(p == null)
//{
// Security.addProvider(new BouncyCastleProvider());
//}
}
公共静态只读字节[] iv_as_AllZEROS = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
公共静态布尔verifyDataRSA(byte [] data,byte [] singature,string publicKey)
{
RSACryptoServiceProvider RSAalg =新的RSACryptoServiceProvider();
if(data == null){
引发新的Exception(数据为空");
}
if(data.Length == 0){
抛出新的Exception(数据长度为零");
}
if(singature == null){
抛出新的Exception("Signature is empty");
}
if(singature.Length == 0){
抛出新的Exception(签名长度为零");
}
如果(publicKey == null){
抛出新的异常(证书公钥为空");
}
//if(RSAalg.SignatureAlgorithm.Equals(" http://www.w3.org/2000/09/xmldsig#rsa-sha1 ")){
// 抛出新的异常(证书算法不是RSA");
//}
尝试
{
RSAalg.FromXmlString(publicKey);
返回RSAalg.VerifyData(data,"SHA1",singature);
//Signature sig = Signature.getInstance("SHA1WithRSA","BC");
//sig.initVerify(publicKey);
//sig.update(data);
//返回sig.verify(singature);
}
catch(ex ex例外){
扔前;
}
}
公共静态字节[]解密RSA(加密的字节[],字符串privateKey)
{
RSACryptoServiceProvider RSA =新的RSACryptoServiceProvider();
if(encrypted == null){
引发新的Exception(数据为空");
}
if(encrypted.Length == 0){
抛出新的Exception(数据长度为零");
}
if(privateKey == null){
抛出新的异常(证书私钥为空");
}
//if(RSA.SignatureAlgorithm.Equals(" http://www.w3.org/2000/09/xmldsig#rsa-sha1 ")){
// 抛出新的异常(证书算法不是RSA");
// } RSA.SignatureAlgorithm始终为" http://www.w3.org/2000/09/xmldsig#rsa -sha1 ""
尝试
{
RSA.FromXmlString(privateKey);
退货RSA.Decrypt(encrypted,RSAEncryptionPadding.OaepSHA1);
//byte [] encryptionByte = null;
//密码cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//cipher.init(2,privateKey);
//byte [] someDecrypted = cipher.update(encrypted);
//byte [] moreDecrypted = cipher.doFinal();
//byte []解密=新的byte [someDecrypted.length + moreDecrypted.length];
//System.arraycopy(someDecrypted、0、decrypted、0、someDecrypted.length);
//System.arraycopy(moreDecrypted,0,解密,someDecrypted.length,moreDecrypted.length);
//返回解密;
}
catch(ex ex例外){
扔前;
}
}
公共静态字节[] signDataRSA(字节[]数据,字符串privateKey)
{
RSACryptoServiceProvider RSAalg =新的RSACryptoServiceProvider();
if(data == null){
引发新的异常(数据为空");
}
if(data.Length == 0){
引发新的Exception(数据长度为零");
}
if(privateKey == null){
抛出新的异常(证书私钥为空");
}
//if(!RSAalg.SignatureAlgorithm.Equals("RSA")){
// 抛出新的异常(证书算法不是RSA");
// }
尝试
{
RSAalg.FromXmlString(privateKey);
返回RSAalg.SignData(data,"SHA1");
//Signature signature = Signature.getInstance("SHA1WithRSA","BC");
//signature.initSign(privateKey);
//signature.update(data);
//返回signature.sign();
}
catch(ex ex例外){
扔前;
}
}
公共静态字节[] cryptoRSA(字节[] plainData,字符串pubKey)
{
if(plainData == null){
引发新的Exception(数据为空");
}
如果(plainData.Length == 0){
抛出新的Exception(数据长度为零");
}
如果(pubKey == null){
抛出新的异常(证书公钥为空");
}
尝试
{
使用(RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
如果(!RSA.SignatureAlgorithm.Equals("RSA"))
{
抛出新的异常(证书算法不是RSA");
}
RSA.FromXmlString(pubKey);
退货RSA.Encrypt(plainData,RSAEncryptionPadding.OaepSHA1);
}
//byte [] encryptionByte = null;
//密码cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//cipher.init(1,pubKey);
//byte [] someData = cipher.update(plainData);
//byte [] moreData = cipher.doFinal();
//byte []加密=新的byte [someData.length + moreData.length];
//System.arraycopy(someData,0,加密,0,someData.length);
//System.arraycopy(moreData,0,加密,someData.length,moreData.length);
//返回加密;
}
catch(ex ex例外){
扔前;
}
}
公共静态字节[]解密AES(字节[]密钥,字节[]加密,字节[] iv)
{
if(key == null){
抛出新的Exception("Key is empty");
}
if(((key.Length!= 16)&&(key.Length!= 24)&&(key.Length!= 32)){
抛出新的异常(密钥长度无效.只能为16,24或32.");
}
如果(iv == null){
抛出新的异常("IV为空");
}
引发新的Exception(数据为空");
}
尝试
{
Aes aes = new AesCryptoServiceProvider();
aes.Key =键;
aes.IV = iv;
byte [] cryptobytes;
使用(MemoryStream ms = new MemoryStream(encrypted))
{
使用(CryptoStream cs = new CryptoStream(ms,aes.CreateDecryptor(),CryptoStreamMode.Read))
{
b使用(StreamReader reader = new StreamReader(cs))
b {
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;字符串结果= reader.ReadToEnd();
b&b ; cryptoBytes = GetBytes(result);
b&b ; 返回cryptoBytes;
b }
}
}
//SecretKeySpec skeySpec = new SecretKeySpec(key,"AES");
//密码cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//IvParameterSpec ivspec =新的IvParameterSpec(iv);
//cipher.init(2,skeySpec,ivspec);
//返回cipher.doFinal(已加密);
}
catch(异常e){
抛出e;
}
}
#region other
///< summary>
///
///</summary>
///< param name =输入"></param>
///< returns></returns>
公共静态字节[] GetBytes(字符串输入)
{
string [] sInput = input.Split(-" .. ToCharArray());
byte [] inputBytes =新的byte [sInput.Length];
为(int i = 0; i< sInput.Length; i ++)
{
inputBytes [i] = byte.Parse(sInput [i],NumberStyles.HexNumber);
}
返回inputBytes;
}
#endregion
公共静态字节[] generateKeyAESKey(字节[]密码,字节[] iv,int迭代计数,int keyLength)
{
如果(密码==空)
{
抛出新的Exception("Password is empty");
}
如果(password.Length == 0)
{
抛出新的Exception(密码长度为零");
}
如果(iv == null)
{
抛出新的异常("IV为空");
}
如果(iv.Length == 0)
{
抛出新的异常("IV的长度为零");
}
如果(iterationCount< 1000)
{
引发新的异常(迭代计数应小于1000");
}
if(((keyLength!= 128)&&(keyLength!= 192)&&(keyLength!= 256))
{
抛出新的异常(密钥长度无效.它只能是128或192或256.");
}
尝试
{
PasswordDeriveBytes a = new PasswordDeriveBytes(password,iv);
返回a.CryptDeriveKey("SHA1","AES",keyLength,iv);
//KeySpec keySpec = new PBEKeySpec(password,iv,erationCount,keyLength);
//SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
//byte [] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
//SecretKey skey = new SecretKeySpec(keyBytes,"AES");
//返回skey.getEncoded();
}
捕获(异常e)
{
}
}
公共静态字节[] cryptoAES(字节[]密钥,字节[]清除,字节[] iv)
{
如果(键==空)
{
抛出新的Exception("Key is empty");
}
if((key.Length!= 16)&&(key.Length!= 24)&&(key.Length!= 32))
{
抛出新的异常(密钥长度无效.只能为16,24或32.");
}
如果(iv == null)
{
抛出新的异常("IV为空");
}
如果(清除== null)
{
引发新的Exception(数据为空");
}
尝试
{
使用(AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key =键;
aesAlg.IV = iv;
ICryptoTransform encryptionor = aesAlg.CreateEncryptor(aesAlg.Key,aesAlg.IV);
使用(MemoryStream msEncrypt = new MemoryStream())
{
b使用(CryptoStream csEncrypt = new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write))
b {
b&b ; 使用(StreamWriter swEncrypt = new StreamWriter(csEncrypt))
b&b ; {
b ; swEncrypt.Write(clear);
b&b ; }
b&b ; 字节[]加密= msEncrypt.ToArray();
b&b ; 返回加密的内容;
b }
}
}
//SecretKeySpec skeySpec = new SecretKeySpec(key,"AES");
//密码cipher = Cipher.getInstance("AES/CBC/PKCS5Padding","BC");
//IvParameterSpec ivspec =新的IvParameterSpec(iv);
//cipher.init(1,skeySpec,ivspec);
//返回cipher.doFinal(clear);
}
捕获(异常e)
{
抛出e;
}
}
}}
package com.axis.security;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class SGSecuror
{
public static final byte[] iv_as_AllZEROS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static {
Provider p = Security.getProvider("BC");
if (p == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
public static boolean verifyDataRSA(byte[] data, byte[] singature, PublicKey publicKey) throws Exception
{
if (data == null) {
throw new Exception("Data is empty");
}
if (data.length == 0) {
throw new Exception("Data length is zero");
}
if (singature == null) {
throw new Exception("Signature is empty");
}
if (singature.length == 0) {
throw new Exception("Signature length is zero");
}
if (publicKey == null) {
throw new Exception("Certificate Public Key is empty");
}
if (publicKey.getAlgorithm().compareTo("RSA") != 0) {
throw new Exception("Certificate Algorithm is not RSA");
}
try
{
Signature sig = Signature.getInstance("SHA1WithRSA", "BC");
sig.initVerify(publicKey);
sig.update(data);
return sig.verify(singature);
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] decryptRSA(byte[] encrypted, PrivateKey privateKey) throws Exception
{
if (encrypted == null) {
throw new Exception("Data is empty");
}
if (encrypted.length == 0) {
throw new Exception("Data length is zero");
}
if (privateKey == null) {
throw new Exception("Certificate Private Key is empty");
}
if (privateKey.getAlgorithm().compareTo("RSA") != 0) {
throw new Exception("Certificate Algorithm is not RSA");
}
try {
byte[] encryptionByte = null;
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(2, privateKey);
byte[] someDecrypted = cipher.update(encrypted);
byte[] moreDecrypted = cipher.doFinal();
byte[] decrypted = new byte[someDecrypted.length + moreDecrypted.length];
System.arraycopy(someDecrypted, 0, decrypted, 0, someDecrypted.length);
System.arraycopy(moreDecrypted, 0, decrypted, someDecrypted.length, moreDecrypted.length);
return decrypted;
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] signDataRSA(byte[] data, PrivateKey privateKey) throws Exception {
if (data == null) {
throw new Exception("Data is empty");
}
if (data.length == 0) {
throw new Exception("Data length is zero");
}
if (privateKey == null) {
throw new Exception("Certificate Private Key is empty");
}
if (privateKey.getAlgorithm().compareTo("RSA") != 0) {
throw new Exception("Certificate Algorithm is not RSA");
}
try
{
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] encryptRSA(byte[] plainData, PublicKey pubKey) throws Exception {
if (plainData == null) {
throw new Exception("Data is empty");
}
if (plainData.length == 0) {
throw new Exception("Data length is zero");
}
if (pubKey == null) {
throw new Exception("Certificate Public Key is empty");
}
if (pubKey.getAlgorithm().compareTo("RSA") != 0) {
throw new Exception("Certificate Algorithm is not RSA");
}
try
{
byte[] encryptionByte = null;
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(1, pubKey);
byte[] someData = cipher.update(plainData);
byte[] moreData = cipher.doFinal();
byte[] encrypted = new byte[someData.length + moreData.length];
System.arraycopy(someData, 0, encrypted, 0, someData.length);
System.arraycopy(moreData, 0, encrypted, someData.length, moreData.length);
return encrypted;
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] decryptAES(byte[] key, byte[] encrypted, byte[] iv)
throws Exception
{
if (key == null) {
throw new Exception("Key is empty");
}
if ((key.length != 16) && (key.length != 24) && (key.length != 32)) {
throw new Exception("Key Length is invalid. It can be only 16,24 or 32.");
}
if (iv == null) {
throw new Exception("IV is empty");
}
if (encrypted == null) {
throw new Exception("Data is empty");
}
try
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(2, skeySpec, ivspec);
return cipher.doFinal(encrypted);
}
catch (Exception e) {
throw e;
}
}
public static byte[] generateKeyAESKey(char[] password, byte[] iv, int iterationCount, int keyLength) throws Exception
{
if (password == null) {
throw new Exception("Password is empty");
}
if (password.length == 0) {
throw new Exception("Password has zero length");
}
if (iv == null) {
throw new Exception("IV is empty");
}
if (iv.length == 0) {
throw new Exception("IV has zero length");
}
if (iterationCount < 1000) {
throw new Exception("Iteration Count should be minimum than 1000");
}
if ((keyLength != 128) && (keyLength != 192) && (keyLength != 256)) {
throw new Exception("Key Length is invalid. It can be only 128 or 192 or 256.");
}
try
{
KeySpec keySpec = new PBEKeySpec(password, iv, iterationCount, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey skey = new SecretKeySpec(keyBytes, "AES");
return skey.getEncoded();
}
catch (Exception e)
{
throw e;
}
}
public static byte[] encryptAES(byte[] key, byte[] clear, byte[] iv) throws Exception
{
if (key == null) {
throw new Exception("Key is empty");
}
if ((key.length != 16) && (key.length != 24) && (key.length != 32)) {
throw new Exception("Key Length is invalid. It can be only 16,24 or 32.");
}
if (iv == null) {
throw new Exception("IV is empty");
}
if (clear == null) {
throw new Exception("Data is empty");
}
try
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(1, skeySpec, ivspec);
return cipher.doFinal(clear);
}
catch (Exception e) {
throw e;
}
}
public SGSecuror() {}
}
Hi Vikas Salve,
Thank you for posting here.
Here is my code to translate it into c#, and some places you may also need to modify according to your needs, for your reference.
The following is the modified code:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
//import java.security.PrivateKey;
// import java.security.Provider;
// import java.security.PublicKey;
// import java.security.Security;
// import java.security.Signature;
// import java.security.spec.KeySpec;
// import javax.crypto.Cipher;
// import javax.crypto.SecretKey;
// import javax.crypto.SecretKeyFactory;
// import javax.crypto.spec.IvParameterSpec;
// import javax.crypto.spec.PBEKeySpec;
// import javax.crypto.spec.SecretKeySpec;
// import org.bouncycastle.jce.provider.BouncyCastleProvider;
namespace ConsoleApplication14与java相等的加密
{
public class SGSecuror
{
public SGSecuror()
{
//Provider p = Security.getProvider("BC");
//if (p == null)
//{
// Security.addProvider(new BouncyCastleProvider());
//}
}
public static readonly byte[] iv_as_AllZEROS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public static bool verifyDataRSA(byte[] data, byte[] singature, string publicKey)
{
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
if (data == null) {
throw new Exception("Data is empty");
}
if (data.Length == 0) {
throw new Exception("Data length is zero");
}
if (singature == null) {
throw new Exception("Signature is empty");
}
if (singature.Length == 0) {
throw new Exception("Signature length is zero");
}
if (publicKey == null) {
throw new Exception("Certificate Public Key is empty");
}
//if (RSAalg.SignatureAlgorithm.Equals("http://www.w3.org/2000/09/xmldsig#rsa-sha1")) {
// throw new Exception("Certificate Algorithm is not RSA");
//}
try
{
RSAalg.FromXmlString(publicKey);
return RSAalg.VerifyData(data, "SHA1", singature);
//Signature sig = Signature.getInstance("SHA1WithRSA", "BC");
//sig.initVerify(publicKey);
//sig.update(data);
//return sig.verify(singature);
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] decryptRSA(byte[] encrypted, string privateKey)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
if (encrypted == null) {
throw new Exception("Data is empty");
}
if (encrypted.Length == 0) {
throw new Exception("Data length is zero");
}
if (privateKey == null) {
throw new Exception("Certificate Private Key is empty");
}
//if (RSA.SignatureAlgorithm.Equals("http://www.w3.org/2000/09/xmldsig#rsa-sha1") ) {
// throw new Exception("Certificate Algorithm is not RSA");
// } RSA.SignatureAlgorithm always is "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
try
{
RSA.FromXmlString(privateKey);
return RSA.Decrypt(encrypted,RSAEncryptionPadding.OaepSHA1);
//byte[] encryptionByte = null;
//Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//cipher.init(2, privateKey);
//byte[] someDecrypted = cipher.update(encrypted);
//byte[] moreDecrypted = cipher.doFinal();
//byte[] decrypted = new byte[someDecrypted.length + moreDecrypted.length];
//System.arraycopy(someDecrypted, 0, decrypted, 0, someDecrypted.length);
//System.arraycopy(moreDecrypted, 0, decrypted, someDecrypted.length, moreDecrypted.length);
//return decrypted;
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] signDataRSA(byte[] data, string privateKey)
{
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
if (data == null) {
throw new Exception("Data is empty");
}
if (data.Length == 0) {
throw new Exception("Data length is zero");
}
if (privateKey == null) {
throw new Exception("Certificate Private Key is empty");
}
//if (!RSAalg.SignatureAlgorithm.Equals("RSA")) {
// throw new Exception("Certificate Algorithm is not RSA");
// }
try
{
RSAalg.FromXmlString(privateKey);
return RSAalg.SignData(data, "SHA1");
//Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
//signature.initSign(privateKey);
//signature.update(data);
//return signature.sign();
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] encryptRSA(byte[] plainData, string pubKey)
{
if (plainData == null) {
throw new Exception("Data is empty");
}
if (plainData.Length == 0) {
throw new Exception("Data length is zero");
}
if (pubKey == null) {
throw new Exception("Certificate Public Key is empty");
}
try
{
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
if (!RSA.SignatureAlgorithm.Equals("RSA"))
{
throw new Exception("Certificate Algorithm is not RSA");
}
RSA.FromXmlString(pubKey);
return RSA.Encrypt(plainData, RSAEncryptionPadding.OaepSHA1);
}
//byte[] encryptionByte = null;
//Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//cipher.init(1, pubKey);
//byte[] someData = cipher.update(plainData);
//byte[] moreData = cipher.doFinal();
//byte[] encrypted = new byte[someData.length + moreData.length];
//System.arraycopy(someData, 0, encrypted, 0, someData.length);
//System.arraycopy(moreData, 0, encrypted, someData.length, moreData.length);
//return encrypted;
}
catch (Exception ex) {
throw ex;
}
}
public static byte[] decryptAES(byte[] key, byte[] encrypted, byte[] iv)
{
if (key == null) {
throw new Exception("Key is empty");
}
if ((key.Length != 16) && (key.Length != 24) && (key.Length != 32)) {
throw new Exception("Key Length is invalid. It can be only 16,24 or 32.");
}
if (iv == null) {
throw new Exception("IV is empty");
}
if (encrypted == null) {
throw new Exception("Data is empty");
}
try
{
Aes aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
byte[] decryptBytes;
using (MemoryStream ms = new MemoryStream(encrypted))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
string result = reader.ReadToEnd() ;
decryptBytes = GetBytes(result);
return decryptBytes;
}
}
}
//SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
//Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//IvParameterSpec ivspec = new IvParameterSpec(iv);
//cipher.init(2, skeySpec, ivspec);
//return cipher.doFinal(encrypted);
}
catch (Exception e) {
throw e;
}
}
#region other
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] GetBytes(string input)
{
string[] sInput = input.Split("-".ToCharArray());
byte[] inputBytes = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
return inputBytes;
}
#endregion
public static byte[] generateKeyAESKey(byte[] password, byte[] iv, int iterationCount, int keyLength)
{
if (password == null)
{
throw new Exception("Password is empty");
}
if (password.Length == 0)
{
throw new Exception("Password has zero length");
}
if (iv == null)
{
throw new Exception("IV is empty");
}
if (iv.Length == 0)
{
throw new Exception("IV has zero length");
}
if (iterationCount < 1000)
{
throw new Exception("Iteration Count should be minimum than 1000");
}
if ((keyLength != 128) && (keyLength != 192) && (keyLength != 256))
{
throw new Exception("Key Length is invalid. It can be only 128 or 192 or 256.");
}
try
{
PasswordDeriveBytes a =new PasswordDeriveBytes(password, iv);
return a.CryptDeriveKey("SHA1","AES",keyLength,iv);
//KeySpec keySpec = new PBEKeySpec(password, iv, iterationCount, keyLength);
//SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
//byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
//SecretKey skey = new SecretKeySpec(keyBytes, "AES");
//return skey.getEncoded();
}
catch (Exception e)
{
throw e;
}
}
public static byte[] encryptAES(byte[] key, byte[] clear, byte[] iv)
{
if (key == null)
{
throw new Exception("Key is empty");
}
if ((key.Length != 16) && (key.Length != 24) && (key.Length != 32))
{
throw new Exception("Key Length is invalid. It can be only 16,24 or 32.");
}
if (iv == null)
{
throw new Exception("IV is empty");
}
if (clear == null)
{
throw new Exception("Data is empty");
}
try
{
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(clear);
}
byte[] encrypted = msEncrypt.ToArray();
return encrypted;
}
}
}
//SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
//Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
//IvParameterSpec ivspec = new IvParameterSpec(iv);
//cipher.init(1, skeySpec, ivspec);
//return cipher.doFinal(clear);
}
catch (Exception e)
{
throw e;
}
}
} }
这篇关于.NET中的Java等效加密代码(rsa/ecb/pkcs1padding C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!