None
으로 설정되면 전송 및 메시지 보안 모두 비활성화됩니다.Widget
서비스에 대한 WCF Basic HTTP Binding의 보안 모드를 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를 사용할 때는 기본 해싱 프로세스의 계산 복잡도를 결정할 때 비용 매개 변수가 중요하다는 점을 기억해야 합니다. 충분한 보안 수준을 보장하려면 비용 매개 변수를 12 이상의 값으로 설정하는 것이 좋습니다. 이 값은 해시 계산에 소요되는 시간에 직접 영향을 주므로 높은 값을 설정하면 잠재적 공격자가 무차별 대입 또는 사전 공격을 수행하는 과정에서 발생하는 계산 비용이 증가합니다.
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 = getenv("SALT");
PKCS5_PBKDF2_HMAC(pass, sizeof(pass), salt, sizeof(salt), ITERATION, EVP_sha512(), outputBytes, digest);
...
Example 1
의 코드는 성공적으로 실행되지만 이 기능을 사용할 수 있는 사용자라면 누구나 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
의 속성을 수정하여 키 또는 암호를 파생하는 데 사용되는 솔트를 조작할 수 있습니다. 프로그램을 공개한 후에는 악의적인 사용자가 암호 해시의 솔트를 알아내었는지 여부를 파악하기가 극도로 어렵기 때문에 사용자 제어 솔트와 관련된 문제를 되돌리기가 힘들 수 있습니다.
app.get('/pbkdf2', function(req, res) {
...
let salt = req.params['salt'];
crypto.pbkdf2(
password,
salt,
iterations,
keyLength,
"sha256",
function (err, derivedKey) { ... }
);
}
Example 1
의 코드는 성공적으로 실행되지만 이 기능을 사용할 수 있는 사용자라면 누구나 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
의 텍스트를 수정하여 키 또는 암호를 파생하는 데 사용되는 솔트를 조작할 수 있습니다. 프로그램을 공개한 후에는 악의적인 사용자가 암호 해시의 솔트를 알아내었는지 여부를 파악하기가 극도로 어렵기 때문에 사용자 제어 솔트와 관련된 문제를 되돌리기가 힘들 수 있습니다.
function register(){
$password = $_GET['password'];
$username = $_GET['username'];
$salt = getenv('SALT');
$hash = hash_pbkdf2('sha256', $password, $salt, 100000);
...
Example 1
의 코드는 성공적으로 실행되지만 이 기능을 사용할 수 있는 사용자라면 누구나 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=io.read
key = OpenSSL::PKCS5::pbkdf2_hmac(pass, salt, iter_count, 256, 'SHA256')
...
Example 1
의 코드는 성공적으로 실행되지만 이 기능을 사용할 수 있는 사용자라면 누구나 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
의 텍스트를 수정하여 키 또는 암호를 파생하는 데 사용되는 솔트를 조작할 수 있습니다. 프로그램을 공개한 후에는 악의적인 사용자가 암호 해시의 솔트를 알아내었는지 여부를 파악하기가 극도로 어렵기 때문에 사용자 제어 솔트와 관련된 문제를 되돌리기가 힘들 수 있습니다.
...
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
) 0만 포함된 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
) 0만 포함된 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)
...