None
,則會停用傳輸和訊息安全性。Widget
服務,將 WCF Basic HTTP 繫結的安全模式設定為 None
。
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.None;
ServiceHost serviceHost = new ServiceHost(typeof(Widget), baseAddress);
serviceHost.AddServiceEndpoint(typeof(Widget), binding, new URI("ExposureAddress"));
<serviceMetadata>
標籤會啟用中繼資料發佈功能。服務中繼資料可能包含不應公開存取的敏感資訊。
ServiceHost myServiceHost = new ServiceHost(typeof(Calculator), baseUri);
ServiceAuthorizationBehavior myServiceBehavior =
myServiceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>();
myServiceBehavior.PrincipalPermissionMode =
PrincipalPermissionMode.None;
<behavior name="DefaultBehavior" returnUnknownExceptionsAsFaults="false">
<serviceCredentials>
<serviceCertificate
x509FindType="FindBySubjectName"
findValue="MyCertificate"
storeLocation="LocalMachine"
storeName="My"/>
<clientCertificate>
<authentication certificateValidationMode="ChainTrust" revocationMode="None"/>
</clientCertificate>
</serviceCredentials>
<metadataPublishing enableGetWsdl="true" enableMetadataExchange="true" enableHelpPage="true"/>
</behavior>
<behaviorExtensions/>
元素會指示 WCF 將自訂行為類別加入特定的 WCF 延伸中。
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="myBehavior" type="MyBehavior" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
...
<security mode="Message">
<message clientCredentialType="UserName" />
...
NSData *imageData = [NSData dataWithContentsOfFile:file];
CC_MD5(imageData, [imageData length], result);
let encodedText = text.cStringUsingEncoding(NSUTF8StringEncoding)
let textLength = CC_LONG(text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLength = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
CC_MD5(encodedText, textLength, result)
...
Rfc2898DeriveBytes rdb8 = new Rfc2898DeriveBytes(password, salt,50);
...
...
#define ITERATION 50
...
PKCS5_PBKDF2_HMAC(pass, sizeof(pass), salt, sizeof(salt), ITERATION, EVP_sha512(), outputBytes, digest);
...
...
final int iterationCount=50;
PBEParameterSpec pbeps=new PBEParameterSpec(salt,iterationCount);
...
...
const iterations = 50;
crypto.pbkdf2(
password,
salt,
iterations,
keyLength,
"sha256",
function (err, derivedKey) { ... }
);
...
#define ITERATION 50
...
CCKeyDerivationPBKDF(kCCPBKDF2,
password,
passwordLen,
salt,
saltLen
kCCPRFHmacAlgSHA256,
ITERATION,
derivedKey,
derivedKeyLen);
...
...
$hash = hash_pbkdf2('sha256', $password, $salt, 50);
...
...
from hashlib import pbkdf2_hmac
dk = pbkdf2_hmac('sha256', password, salt, 50)
...
bcrypt_hash = bcrypt(b64pwd, 11)
bcrypt
API 時,請務必注意,cost 參數在決定底層雜湊程序的運算複雜度中扮演重要角色。強烈建議將 cost 參數設為至少 12 的值,以確保具有足夠的安全層級。此值會直接影響運算雜湊所需的時間,進而使潛在攻擊者執行 Brute-Force 或 Dictionary 攻擊的運算成本更高。
require 'openssl'
...
key = OpenSSL::PKCS5::pbkdf2_hmac(pass, salt, 50, 256, 'SHA256')
...
let ITERATION = UInt32(50)
...
CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2),
password,
passwordLength,
saltBytes,
saltLength,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256),
ITERATION,
derivedKey,
derivedKeyLength)
...
...
<param name="keyObtentionIterations" value="50"/>
...
...
byte[] passwd = Encoding.UTF8.GetBytes(txtPassword.Text);
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(passwd, passwd,10001);
...
...
let password = getPassword();
let salt = password;
crypto.pbkdf2(
password,
salt,
iterations,
keyLength,
"sha256",
function (err, derivedKey) { ... }
);
function register(){
$password = $_GET['password'];
$username = $_GET['username'];
$hash = hash_pbkdf2('sha256', $password, $password, 100000);
...
import hashlib, binascii
def register(request):
password = request.GET['password']
username = request.GET['username']
dk = hashlib.pbkdf2_hmac('sha256', password, password, 100000)
hash = binascii.hexlify(dk)
store(username, hash)
...
require 'openssl'
...
req = Rack::Response.new
password = req.params['password']
...
key = OpenSSL::PKCS5::pbkdf2_hmac(password, password, 100000, 256, 'SHA256')
...
...
string hashname = ConfigurationManager.AppSettings["hash"];
...
HashAlgorithm ha = HashAlgorithm.Create(hashname);
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改屬性 hash
操縱雜湊演算法。程式發佈後,想要復原與使用者控制的演算法相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出特定加密式雜湊的演算法參數。
...
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
String algorithm = prop.getProperty("hash");
...
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(hashInput.getBytes("UTF-8"));
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改屬性 hash
操縱雜湊演算法。程式發佈後,想要復原與使用者控制的演算法相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出特定加密式雜湊的演算法參數。
require 'openssl'
require 'csv'
...
CSV.read(my_file).each do |row|
...
hash = row[4]
...
digest = OpenSSL::Digest.new(hash, data)
...
end
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改 CSV 檔案中的 hash
操縱雜湊演算法。程式發佈後,想要復原與使用者控制的演算法相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出特定加密式雜湊的演算法參數。
string salt = ConfigurationManager.AppSettings["salt"];
...
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("password", Encoding.ASCII.GetBytes(salt));
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改屬性 salt
操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
...
salt = getenv("SALT");
PKCS5_PBKDF2_HMAC(pass, sizeof(pass), salt, sizeof(salt), ITERATION, EVP_sha512(), outputBytes, digest);
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改環境變數 SALT
操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
...
Properties prop = new Properties();
prop.load(new FileInputStream("local.properties"));
String salt = prop.getProperty("salt");
...
PBEKeySpec pbeSpec=new PBEKeySpec(password);
SecretKeyFactory keyFact=SecretKeyFactory.getInstance(CIPHER_ALG);
PBEParameterSpec defParams=new PBEParameterSpec(salt,100000);
Cipher cipher=Cipher.getInstance(CIPHER_ALG);
cipher.init(cipherMode,keyFact.generateSecret(pbeSpec),defParams);
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改屬性 salt
操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
app.get('/pbkdf2', function(req, res) {
...
let salt = req.params['salt'];
crypto.pbkdf2(
password,
salt,
iterations,
keyLength,
"sha256",
function (err, derivedKey) { ... }
);
}
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改屬性 salt
操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
...
@property (strong, nonatomic) IBOutlet UITextField *inputTextField;
...
NSString *salt = _inputTextField.text;
const char *salt_cstr = [salt cStringUsingEncoding:NSUTF8StringEncoding];
...
CCKeyDerivationPBKDF(kCCPBKDF2,
password,
passwordLen,
salt_cstr,
salt.length,
kCCPRFHmacAlgSHA256,
100000,
derivedKey,
derivedKeyLen);
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均將能夠透過修改 UITextField inputTextField
中的文字,操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
function register(){
$password = $_GET['password'];
$username = $_GET['username'];
$salt = getenv('SALT');
$hash = hash_pbkdf2('sha256', $password, $salt, 100000);
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改環境變數 SALT
操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
import hashlib, binascii
def register(request):
password = request.GET['password']
username = request.GET['username']
salt = os.environ['SALT']
dk = hashlib.pbkdf2_hmac('sha256', password, salt, 100000)
hash = binascii.hexlify(dk)
store(username, hash)
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改環境變數 SALT
操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
...
salt=io.read
key = OpenSSL::PKCS5::pbkdf2_hmac(pass, salt, iter_count, 256, 'SHA256')
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均能夠透過修改 salt
中的文字操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
...
@IBOutlet weak var inputTextField : UITextField!
...
let salt = (inputTextField.text as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let saltPointer = UnsafePointer<UInt8>(salt.bytes)
let saltLength = size_t(salt.length)
...
let algorithm : CCPBKDFAlgorithm = CCPBKDFAlgorithm(kCCPBKDF2)
let prf : CCPseudoRandomAlgorithm = CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256)
CCKeyDerivationPBKDF(algorithm,
passwordPointer,
passwordLength,
saltPointer,
saltLength,
prf,
100000,
derivedKeyPointer,
derivedKeyLength)
...
Example 1
中的程式碼將成功執行,但可取得此功能的任何人均將能夠透過修改 UITextField inputTextField
中的文字,操縱用於衍生金鑰或密碼的 Salt。程式發佈後,想要復原與使用者控制的 Salt 相關的問題便會相當棘手,因為很難知道惡意使用者是否已判斷出密碼雜湊的 Salt。
...
DSA dsa = new DSACryptoServiceProvider(1024);
...
...
DSA_generate_parameters_ex(dsa, 1024, NULL, 0, NULL, NULL, NULL);
...
...
dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160)
privatekey := new(dsa.PrivateKey)
privatekey.PublicKey.Parameters = *params
dsa.GenerateKey(privatekey, rand.Reader)
...
...
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
SecureRandom random = SecureRandom.getInstance("SHA256PRNG", "SUN");
keyGen.initialize(1024, random);
...
...
from Crypto.PublicKey import DSA
key = DSA.generate(1024)
...
require 'openssl'
...
key = OpenSSL::PKey::DSA.new(1024)
...
...
DSA dsa1 = new DSACryptoServiceProvider(Convert.ToInt32(TextBox1.Text));
...
key_len
,甚至應該隨之有適當的保護,來驗證其為數值且在適合的金鑰大小值範圍內。對於大多數使用案例,這應該是一個夠大的硬式編碼數字。
...
dsa.GenerateParameters(params, rand.Reader, key_len)
privatekey := new(dsa.PrivateKey)
privatekey.PublicKey.Parameters = *params
dsa.GenerateKey(privatekey, rand.Reader)
...
key_len
的能力。在這些案例中,您應該驗證其為數值且在適合的金鑰大小值範圍內。對於大多數使用案例,請選取一個夠大的硬式編碼金鑰大小。
require 'openssl'
...
key_len = io.read.to_i
key = OpenSSL::PKey::DSA.new(key_len)
...
key_len
,甚至應該隨之有適當的保護,來驗證其為數值且在適合的金鑰大小值範圍內。對於大多數使用案例,這應該是一個夠大的硬式編碼數字。
...
CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
key,
kCCKeySizeDES, // 64-bit key size
iv,
plaintext,
sizeof(plaintext),
ciphertext,
sizeof(ciphertext),
&numBytesEncrypted);
...
...
let iv = getTrueRandomIV()
...
let cStatus = CCCrypt(UInt32(kCCEncrypt),
UInt32(kCCAlgorithmDES),
UInt32(kCCOptionPKCS7Padding),
key,
keyLength,
iv,
plaintext,
plaintextLength,
ciphertext,
ciphertextLength,
&numBytesEncrypted)
...
static public byte[] EncryptWithRSA(byte[] plaintext, RSAParameters key) {
try {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(key);
return rsa.Encrypt(plaintext, false);
}
catch(CryptographicException e) {
Console.WriteLine(e.Message);
return null;
}
}
void encrypt_with_rsa(BIGNUM *out, BIGNUM *in, RSA *key) {
u_char *inbuf, *outbuf;
int ilen;
...
ilen = BN_num_bytes(in);
inbuf = xmalloc(ilen);
BN_bn2bin(in, inbuf);
if ((len = RSA_public_encrypt(ilen, inbuf, outbuf, key, RSA_NO_PADDING)) <= 0) {
fatal("encrypt_with_rsa() failed");
}
...
}
...
import "crypto/rsa"
...
plaintext := []byte("Attack at dawn")
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, &k.PublicKey, plaintext)
...
public Cipher getRSACipher() {
Cipher rsa = null;
try {
rsa = javax.crypto.Cipher.getInstance("RSA/NONE/NoPadding");
}
catch (java.security.NoSuchAlgorithmException e) {
log("this should never happen", e);
}
catch (javax.crypto.NoSuchPaddingException e) {
log("this should never happen", e);
}
return rsa;
}
+ (NSData *) encryptData:(NSData *) plaintextData withKey:(SecKeyRef *) publicKey {
CFErrorRef error = nil;
NSData *ciphertextData = (NSData*) CFBridgingRelease(
SecKeyCreateEncryptedData(*publicKey,
kSecKeyAlgorithmRSAEncryptionPKCS1,
(__bridge CFDataRef) plaintextData,
&error));
if (error) {
// handle error ...
}
return ciphertextData;
}
function encrypt($input, $key) {
$output='';
openssl_public_encrypt($input, $output, $key, OPENSSL_NO_PADDING);
return $output;
}
...
from Crypto.PublicKey import RSA
message = 'Attack at dawn'
key = RSA.importKey(open('pubkey.der').read())
ciphertext = key.encrypt(message)
...
require 'openssl'
...
key = OpenSSL::PKey::RSA.new 2048
public_encrypted = key.public_encrypt(data) #padding type not specified
...
Example 1
中,OpenSSL::PKey::RSA#public_encrypt
只使用字串進行呼叫,並未指定要使用的填補類型。填補預設為 OpenSSL::PKey::RSA::PKCS1_PADDING
。
func encrypt(data plaintextData:Data, publicKey:SecKey) throws -> Data {
var error: Unmanaged<CFError>?
guard let ciphertextData = SecKeyCreateEncryptedData(publicKey,
.rsaEncryptionPKCS1,
plaintextData as CFData,
&error) else {
throw error!.takeRetainedValue() as Error
}
return ciphertextData as Data;
}
...
Blob iv = Blob.valueOf('1234567890123456');
Blob encrypted = Crypto.encrypt('AES128', encKey, iv, input);
...
byte[] iv = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
using (SymmetricAlgorithm aesAlgo = SymmetricAlgorithm.Create("AES"))
{
...
aesAlgo.IV = iv;
...
}
unsigned char * iv = "12345678";
EVP_EncryptInit_ex(&ctx, EVP_idea_gcm(), NULL, key, iv);
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
...
block, err := aes.NewCipher(key)
...
mode := cipher.NewCBCEncrypter(block, key)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
byte[] iv = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
IvParameterSpec ips = new IvParameterSpec(iv);
...
const iv = "hardcoded"
const cipher = crypto.createCipheriv("aes-192-ccm", key, iv)
...
NSString *iv = @"1234567812345678"; //Bad idea to hard code IV
char ivPtr[kCCBlockSizeAES128];
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSASCIIStringEncoding];
...
ccStatus = CCCrypt( kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
[key cStringUsingEncoding:NSASCIIStringEncoding],
kCCKeySizeAES128,
[ivPtr], /*IV should be something random (not null and not constant)*/
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted
);
nil
),則會使用所有零的 IV。
from Crypto.Cipher import AES
from Crypto import Random
...
key = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CTR, IV=key)
require 'openssl'
...
cipher = OpenSSL::Cipher::AES.new('256-GCM')
cipher.encrypt
@key = cipher.random_key
cipher.iv=@key
encrypted = cipher.update(data) + cipher.final # encrypts data without hardcoded IV
...
...
let cStatus = CCCrypt(UInt32(kCCEncrypt),
UInt32(kCCAlgorithmAES128),
UInt32(kCCOptionPKCS7Padding),
key,
keyLength,
"0123456789012345",
plaintext,
plaintextLength,
ciphertext,
ciphertextLength,
&numBytesEncrypted)
nil
),則會使用所有零的 IV。
...
var objAesCryptoService = new AesCryptoServiceProvider();
objAesCryptoService.Mode = CipherMode.ECB;
objAesCryptoService.Padding = PaddingMode.PKCS7;
objAesCryptoService.Key = securityKeyArray;
var objCrytpoTransform = objAesCryptoService.CreateEncryptor();
...
EVP_EncryptInit_ex(&ctx, EVP_aes_256_ecb(), NULL, key, iv);
...
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
...
...
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key);
...
...
ccStatus = CCCrypt( kCCEncrypt,
kCCAlgorithmAES,
kCCOptionECBMode, // Uses ECB mode
key,
kCCKeySizeAES128,
iv,
plaintext,
sizeof(plaintext),
ciphertext,
sizeof(ciphertext),
&numBytesEncrypted);
...
from Crypto.Cipher import AES
from Crypto import Random
...
key = Random.new().read(AES.block_size)
random_iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_ECB, random_iv)
require 'openssl'
...
cipher = OpenSSL::Cipher::AES.new('256-ECB')
...
ccStatus = CCCrypt(UInt32(kCCEncrypt),
UInt32(kCCAlgorithmAES128),
UInt32(kCCOptionECBMode),
keyData.bytes,
keyLength,
keyData.bytes,
data.bytes,
data.length,
cryptData.mutableBytes,
cryptData.length,
&numBytesEncrypted)
...
static public byte[] EncryptWithRSA(byte[] plaintext, RSAParameters key) {
try {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512);
rsa.ImportParameters(key);
return rsa.Encrypt(plaintext, true);
}
catch(CryptographicException e) {
Console.WriteLine(e.Message);
return null;
}
}
EVP_PKEY * get_RSA_key() {
unsigned long err;
EVP_PKEY * pkey;
RSA * rsa;
rsa = RSA_generate_key(512, 35, NULL, NULL);
if (rsa == NULL) {
err = ERR_get_error();
printf("Error = %s\n",ERR_reason_error_string(err));
return NULL;
}
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
return pkey;
}
...
myPrivateKey := rsa.GenerateKey(rand.Reader, 1024);
...
public static KeyPair getRSAKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair key = keyGen.generateKeyPair();
return key;
}
...
crmfObject = crypto.generateCRMFRequest(
"CN=" + name.value,
password.value,
authenticator,
keyTransportCert,
"setCRMFRequest();",
512, null, "rsa-dual-use");
...
...
CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
key,
kCCKeySizeDES, // 64-bit key size
iv,
plaintext,
sizeof(plaintext),
ciphertext,
sizeof(ciphertext),
&numBytesEncrypted);
...
...
$keysize = 1024;
$options = array('private_key_bits' => $keysize, 'private_key_type' => OPENSSL_KEYTYPE_RSA);
$res = openssl_pkey_new($options);
...
...
from Crypto.PublicKey import RSA
key = RSA.generate(1024)
...
require 'openssl'
...
pkey = OpenSSL::PKey::RSA.new 1024
...
...
let iv = getTrueRandomIV()
...
let cStatus = CCCrypt(UInt32(kCCEncrypt),
UInt32(kCCAlgorithmDES),
UInt32(kCCOptionPKCS7Padding),
key,
UInt32(kCCKeySizeDES), // 64-bit key size
iv,
plaintext,
plaintextLength,
ciphertext,
ciphertextLength,
&numBytesEncrypted)
...