/** * CBC模式加密数据 * @param data 待加密数据 * @param key 密钥 * @param iv 向量 * @param paddingMode 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充 * @return 返回密文值 */ public static byte[] EncryptCBC(byte[] data, byte[] key, byte[] iv, int paddingMode) { IBlockCipher engine = new SM4Engine(); engine.Init(true, new KeyParameter(key)); if (paddingMode == SM4_PKCS8PADDING) { data = padding(data, SM4_ENCRYPT); } else { data = (byte [])data.Clone(); } int length = data.Length; iv = (byte [])iv.Clone(); for (int i = 0; length > 0; length -= 16, i += 16) { for (int j = 0; j < 16; j++) { data[i + j] = ((byte)(data[i + j] ^ iv[j])); } engine.ProcessBlock(data, i, data, i); Buffer.BlockCopy(data, i, iv, 0, 16); } return(data); }
/** * CBC模式解密数据 * @param cipher 密文数据 * @param key 密钥 * @param iv 向量 * @param isPadding 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充 * @return 返回明文字节数据 */ public static byte[] DecryptCBC(byte[] cipher, byte[] key, byte[] iv, int paddingMode) { IBlockCipher engine = new SM4Engine(); engine.Init(false, new KeyParameter(key)); int length = cipher.Length; byte[] plain = new byte[cipher.Length]; iv = (byte [])iv.Clone(); for (int i = 0; length > 0; length -= 16, i += 16) { engine.ProcessBlock(cipher, i, plain, i); for (int j = 0; j < 16; j++) { plain[j + i] = ((byte)(plain[i + j] ^ iv[j])); } Buffer.BlockCopy(cipher, i, iv, 0, 16); } byte[] res = null; if (paddingMode == SM4_PKCS8PADDING) { res = padding(plain, SM4_DECRYPT); } else { res = plain; } return(res); }
private void DoTest1000000() { byte[] plain = Hex.Decode("0123456789abcdeffedcba9876543210"); byte[] key = Hex.Decode("0123456789abcdeffedcba9876543210"); byte[] cipher = Hex.Decode("595298c7c6fd271f0402f804c33d3f66"); byte[] buf = new byte[16]; IBlockCipher engine = new SM4Engine(); engine.Init(true, new KeyParameter(key)); Array.Copy(plain, 0, buf, 0, buf.Length); for (int i = 0; i != 1000000; i++) { engine.ProcessBlock(buf, 0, buf, 0); } if (!AreEqual(cipher, buf)) { Fail("1000000 encryption test failed"); } engine.Init(false, new KeyParameter(key)); for (int i = 0; i != 1000000; i++) { engine.ProcessBlock(buf, 0, buf, 0); } if (!AreEqual(plain, buf)) { Fail("1000000 decryption test failed"); } }
/** * sm4 ecb模式加密数据 * @param data 待加密数据 * @param key sm4密钥 * @param paddingMode 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充 * @return 返回密文数据 */ public static byte[] EncryptECB(byte[] data, byte[] key, int paddingMode) { IBlockCipher engine = new SM4Engine(); engine.Init(true, new KeyParameter(key)); if (paddingMode == SM4_PKCS8PADDING) { data = padding(data, SM4_ENCRYPT); } else { data = (byte [])data.Clone(); } int length = data.Length; for (int i = 0; length > 0; length -= 16, i += 16) { engine.ProcessBlock(data, i, data, i); } return(data); }
/** * sm4 ecb模式解密数据 * @param cipher 密文数据 * @param key sm4密钥 * @param paddingMode 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充 * @return 返回明文字节数据 */ public static byte[] DecryptECB(byte[] cipher, byte[] key, int paddingMode) { IBlockCipher engine = new SM4Engine(); engine.Init(false, new KeyParameter(key)); int length = cipher.Length; byte[] tmp = new byte[cipher.Length]; for (int i = 0; length > 0; length -= 16, i += 16) { engine.ProcessBlock(cipher, i, tmp, i); } byte[] plain = null; if (paddingMode == SM4_PKCS8PADDING) { plain = padding(tmp, SM4_DECRYPT); } else { plain = tmp; } return(plain); }
public static IBufferedCipher GetCipher( string algorithm) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } algorithm = Platform.ToUpperInvariant(algorithm); { string aliased = (string)algorithms[algorithm]; if (aliased != null) { algorithm = aliased; } } IBasicAgreement iesAgreement = null; if (algorithm == "IES") { iesAgreement = new DHBasicAgreement(); } else if (algorithm == "ECIES") { iesAgreement = new ECDHBasicAgreement(); } if (iesAgreement != null) { return(new BufferedIesCipher( new IesEngine( iesAgreement, new Kdf2BytesGenerator( new Sha1Digest()), new HMac( new Sha1Digest())))); } if (Platform.StartsWith(algorithm, "PBE")) { if (Platform.EndsWith(algorithm, "-CBC")) { if (algorithm == "PBEWITHSHA1ANDDES-CBC") { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new DesEngine()))); } else if (algorithm == "PBEWITHSHA1ANDRC2-CBC") { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new RC2Engine()))); } else if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC")) { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new DesEdeEngine()))); } else if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC")) { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new RC2Engine()))); } } else if (Platform.EndsWith(algorithm, "-BC") || Platform.EndsWith(algorithm, "-OPENSSL")) { if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITAES-CBC-BC", "PBEWITHSHAAND192BITAES-CBC-BC", "PBEWITHSHAAND256BITAES-CBC-BC", "PBEWITHSHA256AND128BITAES-CBC-BC", "PBEWITHSHA256AND192BITAES-CBC-BC", "PBEWITHSHA256AND256BITAES-CBC-BC", "PBEWITHMD5AND128BITAES-CBC-OPENSSL", "PBEWITHMD5AND192BITAES-CBC-OPENSSL", "PBEWITHMD5AND256BITAES-CBC-OPENSSL")) { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new AesEngine()))); } } } string[] parts = algorithm.Split('/'); IAeadCipher aeadCipher = null; IBlockCipher blockCipher = null; IAsymmetricBlockCipher asymBlockCipher = null; IStreamCipher streamCipher = null; string algorithmName = parts[0]; { string aliased = (string)algorithms[algorithmName]; if (aliased != null) { algorithmName = aliased; } } CipherAlgorithm cipherAlgorithm; try { cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName); } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } switch (cipherAlgorithm) { case CipherAlgorithm.AES: blockCipher = new AesEngine(); break; case CipherAlgorithm.ARC4: streamCipher = new RC4Engine(); break; case CipherAlgorithm.BLOWFISH: blockCipher = new BlowfishEngine(); break; case CipherAlgorithm.CAMELLIA: blockCipher = new CamelliaEngine(); break; case CipherAlgorithm.CAST5: blockCipher = new Cast5Engine(); break; case CipherAlgorithm.CAST6: blockCipher = new Cast6Engine(); break; case CipherAlgorithm.CHACHA: streamCipher = new ChaChaEngine(); break; case CipherAlgorithm.CHACHA20_POLY1305: aeadCipher = new ChaCha20Poly1305(); break; case CipherAlgorithm.CHACHA7539: streamCipher = new ChaCha7539Engine(); break; case CipherAlgorithm.DES: blockCipher = new DesEngine(); break; case CipherAlgorithm.DESEDE: blockCipher = new DesEdeEngine(); break; case CipherAlgorithm.ELGAMAL: asymBlockCipher = new ElGamalEngine(); break; case CipherAlgorithm.GOST28147: blockCipher = new Gost28147Engine(); break; case CipherAlgorithm.HC128: streamCipher = new HC128Engine(); break; case CipherAlgorithm.HC256: streamCipher = new HC256Engine(); break; case CipherAlgorithm.IDEA: blockCipher = new IdeaEngine(); break; case CipherAlgorithm.NOEKEON: blockCipher = new NoekeonEngine(); break; case CipherAlgorithm.PBEWITHSHAAND128BITRC4: case CipherAlgorithm.PBEWITHSHAAND40BITRC4: streamCipher = new RC4Engine(); break; case CipherAlgorithm.RC2: blockCipher = new RC2Engine(); break; case CipherAlgorithm.RC5: blockCipher = new RC532Engine(); break; case CipherAlgorithm.RC5_64: blockCipher = new RC564Engine(); break; case CipherAlgorithm.RC6: blockCipher = new RC6Engine(); break; case CipherAlgorithm.RIJNDAEL: blockCipher = new RijndaelEngine(); break; case CipherAlgorithm.RSA: asymBlockCipher = new RsaBlindedEngine(); break; case CipherAlgorithm.SALSA20: streamCipher = new Salsa20Engine(); break; case CipherAlgorithm.SEED: blockCipher = new SeedEngine(); break; case CipherAlgorithm.SERPENT: blockCipher = new SerpentEngine(); break; case CipherAlgorithm.SKIPJACK: blockCipher = new SkipjackEngine(); break; case CipherAlgorithm.SM4: blockCipher = new SM4Engine(); break; case CipherAlgorithm.TEA: blockCipher = new TeaEngine(); break; case CipherAlgorithm.THREEFISH_256: blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256); break; case CipherAlgorithm.THREEFISH_512: blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512); break; case CipherAlgorithm.THREEFISH_1024: blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024); break; case CipherAlgorithm.TNEPRES: blockCipher = new TnepresEngine(); break; case CipherAlgorithm.TWOFISH: blockCipher = new TwofishEngine(); break; case CipherAlgorithm.VMPC: streamCipher = new VmpcEngine(); break; case CipherAlgorithm.VMPC_KSA3: streamCipher = new VmpcKsa3Engine(); break; case CipherAlgorithm.XTEA: blockCipher = new XteaEngine(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } if (aeadCipher != null) { if (parts.Length > 1) { throw new ArgumentException("Modes and paddings cannot be applied to AEAD ciphers"); } return(new BufferedAeadCipher(aeadCipher)); } if (streamCipher != null) { if (parts.Length > 1) { throw new ArgumentException("Modes and paddings not used for stream ciphers"); } return(new BufferedStreamCipher(streamCipher)); } bool cts = false; bool padded = true; IBlockCipherPadding padding = null; IAeadBlockCipher aeadBlockCipher = null; if (parts.Length > 2) { if (streamCipher != null) { throw new ArgumentException("Paddings not used for stream ciphers"); } string paddingName = parts[2]; CipherPadding cipherPadding; if (paddingName == "") { cipherPadding = CipherPadding.RAW; } else if (paddingName == "X9.23PADDING") { cipherPadding = CipherPadding.X923PADDING; } else { try { cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName); } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } switch (cipherPadding) { case CipherPadding.NOPADDING: padded = false; break; case CipherPadding.RAW: break; case CipherPadding.ISO10126PADDING: case CipherPadding.ISO10126D2PADDING: case CipherPadding.ISO10126_2PADDING: padding = new ISO10126d2Padding(); break; case CipherPadding.ISO7816_4PADDING: case CipherPadding.ISO9797_1PADDING: padding = new ISO7816d4Padding(); break; case CipherPadding.ISO9796_1: case CipherPadding.ISO9796_1PADDING: asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher); break; case CipherPadding.OAEP: case CipherPadding.OAEPPADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher); break; case CipherPadding.OAEPWITHMD5ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest()); break; case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest()); break; case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest()); break; case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest()); break; case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest()); break; case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest()); break; case CipherPadding.PKCS1: case CipherPadding.PKCS1PADDING: asymBlockCipher = new Pkcs1Encoding(asymBlockCipher); break; case CipherPadding.PKCS5: case CipherPadding.PKCS5PADDING: case CipherPadding.PKCS7: case CipherPadding.PKCS7PADDING: padding = new Pkcs7Padding(); break; case CipherPadding.TBCPADDING: padding = new TbcPadding(); break; case CipherPadding.WITHCTS: cts = true; break; case CipherPadding.X923PADDING: padding = new X923Padding(); break; case CipherPadding.ZEROBYTEPADDING: padding = new ZeroBytePadding(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } string mode = ""; if (parts.Length > 1) { mode = parts[1]; int di = GetDigitIndex(mode); string modeName = di >= 0 ? mode.Substring(0, di) : mode; try { CipherMode cipherMode = modeName == "" ? CipherMode.NONE : (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName); switch (cipherMode) { case CipherMode.ECB: case CipherMode.NONE: break; case CipherMode.CBC: blockCipher = new CbcBlockCipher(blockCipher); break; case CipherMode.CCM: aeadBlockCipher = new CcmBlockCipher(blockCipher); break; case CipherMode.CFB: { int bits = (di < 0) ? 8 * blockCipher.GetBlockSize() : int.Parse(mode.Substring(di)); blockCipher = new CfbBlockCipher(blockCipher, bits); break; } case CipherMode.CTR: blockCipher = new SicBlockCipher(blockCipher); break; case CipherMode.CTS: cts = true; blockCipher = new CbcBlockCipher(blockCipher); break; case CipherMode.EAX: aeadBlockCipher = new EaxBlockCipher(blockCipher); break; case CipherMode.GCM: aeadBlockCipher = new GcmBlockCipher(blockCipher); break; case CipherMode.GOFB: blockCipher = new GOfbBlockCipher(blockCipher); break; case CipherMode.OCB: aeadBlockCipher = new OcbBlockCipher(blockCipher, CreateBlockCipher(cipherAlgorithm)); break; case CipherMode.OFB: { int bits = (di < 0) ? 8 * blockCipher.GetBlockSize() : int.Parse(mode.Substring(di)); blockCipher = new OfbBlockCipher(blockCipher, bits); break; } case CipherMode.OPENPGPCFB: blockCipher = new OpenPgpCfbBlockCipher(blockCipher); break; case CipherMode.SIC: if (blockCipher.GetBlockSize() < 16) { throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)"); } blockCipher = new SicBlockCipher(blockCipher); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } if (aeadBlockCipher != null) { if (cts) { throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers."); } if (padded && parts.Length > 2 && parts[2] != "") { throw new SecurityUtilityException("Bad padding specified for AEAD cipher."); } return(new BufferedAeadBlockCipher(aeadBlockCipher)); } if (blockCipher != null) { if (cts) { return(new CtsBlockCipher(blockCipher)); } if (padding != null) { return(new PaddedBufferedBlockCipher(blockCipher, padding)); } if (!padded || blockCipher.IsPartialBlockOkay) { return(new BufferedBlockCipher(blockCipher)); } return(new PaddedBufferedBlockCipher(blockCipher)); } if (asymBlockCipher != null) { return(new BufferedAsymmetricBlockCipher(asymBlockCipher)); } throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); }
/// <summary> /// Build the engine /// </summary> /// <param name="algorithm">SymmetricBlockAlgorithm enum, algorithm name</param> /// <returns>IBlockCipher with the algorithm Engine</returns> internal IBlockCipher getCipherEngine(SymmetricBlockAlgorithm algorithm) { IBlockCipher engine = null; switch (algorithm) { case SymmetricBlockAlgorithm.AES: engine = new AesEngine(); break; case SymmetricBlockAlgorithm.BLOWFISH: engine = new BlowfishEngine(); break; case SymmetricBlockAlgorithm.CAMELLIA: engine = new CamelliaEngine(); break; case SymmetricBlockAlgorithm.CAST5: engine = new Cast5Engine(); break; case SymmetricBlockAlgorithm.CAST6: engine = new Cast6Engine(); break; case SymmetricBlockAlgorithm.DES: engine = new DesEngine(); break; case SymmetricBlockAlgorithm.TRIPLEDES: engine = new DesEdeEngine(); break; case SymmetricBlockAlgorithm.DSTU7624_128: engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_128, this.error)); break; case SymmetricBlockAlgorithm.DSTU7624_256: engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_256, this.error)); break; case SymmetricBlockAlgorithm.DSTU7624_512: engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_512, this.error)); break; case SymmetricBlockAlgorithm.GOST28147: engine = new Gost28147Engine(); break; case SymmetricBlockAlgorithm.NOEKEON: engine = new NoekeonEngine(); break; case SymmetricBlockAlgorithm.RC2: engine = new RC2Engine(); break; case SymmetricBlockAlgorithm.RC532: engine = new RC532Engine(); break; case SymmetricBlockAlgorithm.RC564: engine = new RC564Engine(); break; case SymmetricBlockAlgorithm.RC6: engine = new RC6Engine(); break; case SymmetricBlockAlgorithm.RIJNDAEL_128: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_128, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_160: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_160, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_192: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_192, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_224: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_224, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_256: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_256, this.error)); break; case SymmetricBlockAlgorithm.SEED: engine = new SeedEngine(); break; case SymmetricBlockAlgorithm.SERPENT: engine = new SerpentEngine(); break; case SymmetricBlockAlgorithm.SKIPJACK: engine = new SkipjackEngine(); break; case SymmetricBlockAlgorithm.SM4: engine = new SM4Engine(); break; case SymmetricBlockAlgorithm.TEA: engine = new TeaEngine(); break; case SymmetricBlockAlgorithm.THREEFISH_256: engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_256, this.error)); break; case SymmetricBlockAlgorithm.THREEFISH_512: engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_512, this.error)); break; case SymmetricBlockAlgorithm.THREEFISH_1024: engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_1024, this.error)); break; case SymmetricBlockAlgorithm.TWOFISH: engine = new TwofishEngine(); break; case SymmetricBlockAlgorithm.XTEA: engine = new XteaEngine(); break; default: this.error.setError("SB020", "Cipher " + algorithm + " not recognised."); break; } return(engine); }