当前位置: 首页>>代码示例>>Java>>正文


Java Cipher类代码示例

本文整理汇总了Java中javacardx.crypto.Cipher的典型用法代码示例。如果您正苦于以下问题:Java Cipher类的具体用法?Java Cipher怎么用?Java Cipher使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Cipher类属于javacardx.crypto包,在下文中一共展示了Cipher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: n_mod_exp

import javacardx.crypto.Cipher; //导入依赖的package包/类
/**
 * Calculates {@code res := base ** exp mod mod} using RSA engine. 
 * Requirements:
 * 1. Modulo must be either 521, 1024, 2048 or other lengths supported by RSA (see appendzeros() and mod() method)
 * 2. Base must have the same size as modulo (see prependzeros())
 * @param baseLen   length of base rounded to size of RSA engine
 * @param base      value of base (if size is not equal to baseLen then zeroes are appended)
 * @param exponent  array with exponent
 * @param exponentLen length of exponent
 * @param modulo    value of modulo 
 * @param resultArray array for the computed result
 * @param resultOffset start offset of resultArray
 */
private short n_mod_exp(short baseLen, Bignat base, byte[] exponent, short exponentLen, Bignat modulo, byte[] resultArray, short resultOffset) {
    // Verify if pre-allocated engine match the required values
    if (bnh.fnc_NmodE_pubKey.getSize() < (short) (modulo.length() * 8)) {
        // attempt to perform modulu with higher or smaller than supported length - try change constant MODULO_ENGINE_MAX_LENGTH
        ISOException.throwIt(ReturnCodes.SW_BIGNAT_MODULOTOOLARGE);
    }
    if (bnh.fnc_NmodE_pubKey.getSize() < (short) (base.length() * 8)) {
        ISOException.throwIt(ReturnCodes.SW_BIGNAT_MODULOTOOLARGE);
    }
    // Potential problem: we are changing key value for publicKey already used before with occ.bnHelper.modCipher. 
    // Simulator and potentially some cards fail to initialize this new value properly (probably assuming that same key object will always have same value)
    // Fix (if problem occure): generate new key object: RSAPublicKey publicKey = (RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, (short) (baseLen * 8), false);

    bnh.fnc_NmodE_pubKey.setExponent(exponent, (short) 0, exponentLen);
    bnh.lock(bnh.fnc_deep_resize_tmp);
    modulo.append_zeros(baseLen, bnh.fnc_deep_resize_tmp, (short) 0);
    bnh.fnc_NmodE_pubKey.setModulus(bnh.fnc_deep_resize_tmp, (short) 0, baseLen);
    bnh.fnc_NmodE_cipher.init(bnh.fnc_NmodE_pubKey, Cipher.MODE_DECRYPT);        
    base.prepend_zeros(baseLen, bnh.fnc_deep_resize_tmp, (short) 0);
    // BUGBUG: Check if input is not all zeroes (causes out-of-bound exception on some cards)
    short len = bnh.fnc_NmodE_cipher.doFinal(bnh.fnc_deep_resize_tmp, (short) 0, baseLen, resultArray, resultOffset); 
    bnh.unlock(bnh.fnc_deep_resize_tmp);
    return len;
}
 
开发者ID:OpenCryptoProject,项目名称:JCMathLib,代码行数:38,代码来源:Bignat.java

示例2: n_mod_exp

import javacardx.crypto.Cipher; //导入依赖的package包/类
/**
 * Calculates {@code res := base ** exp mod mod} using RSA engine. 
 * Requirements:
 * 1. Modulo must be either 521, 1024, 2048 or other lengths supported by RSA (see appendzeros() and mod() method)
 * 2. Base must have the same size as modulo (see prependzeros())
 * @param baseLen   length of base rounded to size of RSA engine
 * @param base      value of base (if size is not equal to baseLen then zeroes are appended)
 * @param exponent  array with exponent
 * @param exponentLen length of exponent
 * @param modulo    value of modulo 
 * @param resultArray array for the computed result
 * @param resultOffset start offset of resultArray
 */
private short n_mod_exp(short baseLen, Bignat base, byte[] exponent, short exponentLen, Bignat modulo, byte[] resultArray, short resultOffset) {
    // Verify if pre-allocated engine match the required values
    if (bnh.fnc_NmodE_pubKey.getSize() < (short) (modulo.length() * 8)) {
        // attempt to perform modulu with higher or smaller than supported length - try change constant MODULO_ENGINE_MAX_LENGTH
        ISOException.throwIt(ReturnCodes.SW_BIGNAT_MODULOTOOLARGE);
    }
    if (bnh.fnc_NmodE_pubKey.getSize() < (short) (base.length() * 8)) {
        ISOException.throwIt(ReturnCodes.SW_BIGNAT_MODULOTOOLARGE);
    }
    // Potential problem: we are changing key value for publicKey already used before with occ.bnHelper.modCipher. 
    // Simulator and potentially some cards fail to initialize this new value properly (probably assuming that same key object will always have same value)
    // Fix (if problem occure): generate new key object: RSAPublicKey publicKey = (RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, (short) (baseLen * 8), false);
    
    bnh.fnc_NmodE_pubKey.setExponent(exponent, (short) 0, exponentLen);
    bnh.lock(bnh.fnc_deep_resize_tmp);
    modulo.append_zeros(baseLen, bnh.fnc_deep_resize_tmp, (short) 0);
    bnh.fnc_NmodE_pubKey.setModulus(bnh.fnc_deep_resize_tmp, (short) 0, baseLen);
    bnh.fnc_NmodE_cipher.init(bnh.fnc_NmodE_pubKey, Cipher.MODE_DECRYPT);        
    base.prepend_zeros(baseLen, bnh.fnc_deep_resize_tmp, (short) 0);
    // BUGBUG: Check if input is not all zeroes (causes out-of-bound exception on some cards)
    short len = bnh.fnc_NmodE_cipher.doFinal(bnh.fnc_deep_resize_tmp, (short) 0, baseLen, resultArray, resultOffset); 
    bnh.unlock(bnh.fnc_deep_resize_tmp);
    return len;
}
 
开发者ID:OpenCryptoProject,项目名称:Myst,代码行数:38,代码来源:jcmathlib.java

示例3: KeepassNFC

import javacardx.crypto.Cipher; //导入依赖的package包/类
protected KeepassNFC(byte[] bArray, short bOffset, byte bLength)
{
	card_key = new KeyPair(RSA_ALGORITHM, RSA_KEYLENGTH);
	password_key = (AESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_128, false);
	transaction_key = (AESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_AES_TRANSIENT_DESELECT, KeyBuilder.LENGTH_AES_128, false);

	card_cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
	password_cipher = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
	transaction_cipher = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);

	scratch_area = JCSystem.makeTransientByteArray((short)260, JCSystem.CLEAR_ON_DESELECT);
	aes_key_temporary = JCSystem.makeTransientByteArray((short)260, JCSystem.CLEAR_ON_DESELECT);
	card_cipher_initialised = false;

	/* Generate RSA keypair on install, as if generateCardKey was called. */
	card_key.genKeyPair();

	register();
}
 
开发者ID:nfd,项目名称:smartcard_crypto_applet,代码行数:20,代码来源:KeepassNFC.java

示例4: prepareDecryption

import javacardx.crypto.Cipher; //导入依赖的package包/类
protected void prepareDecryption(APDU apdu)
{
	/* Decrypt the transaction key and set up AES engines for decryption.
	 *
	 * scratch area contains: transaction key, encrypted with card key
	 * 16 bytes: IV for transaction key (plaintext)
	 * 16 bytes: IV for password key (plaintext)
	*/
	byte[] buffer = apdu.getBuffer();
	short length  = apdu.setIncomingAndReceive();

	if(length == 32) {
		decryptWithCardKey(scratch_area, (short)0, aes_key_temporary);
		transaction_key.setKey(aes_key_temporary, (short)0);

		transaction_cipher.init(transaction_key, Cipher.MODE_ENCRYPT, buffer, (short)(ISO7816.OFFSET_CDATA + 0), (short)16);
		password_cipher.init(password_key, Cipher.MODE_DECRYPT, buffer, (short)(ISO7816.OFFSET_CDATA + 16), (short)16);

		buffer[RESPONSE_STATUS_OFFSET] = RESPONSE_SUCCEEDED;
	} else {
		buffer[ISO7816.OFFSET_CDATA] = RESPONSE_FAILED;
	}

	apdu.setOutgoingAndSend((short)ISO7816.OFFSET_CDATA, (short)1);
}
 
开发者ID:nfd,项目名称:smartcard_crypto_applet,代码行数:26,代码来源:KeepassNFC.java

示例5: OpenPGPSecureMessaging

import javacardx.crypto.Cipher; //导入依赖的package包/类
/**
 * Construct a new secure messaging wrapper.
 */
public OpenPGPSecureMessaging() {
    ssc = JCSystem.makeTransientByteArray(SSC_SIZE, 
            JCSystem.CLEAR_ON_DESELECT);
    tmp = JCSystem.makeTransientByteArray(TMP_SIZE, 
            JCSystem.CLEAR_ON_DESELECT);
    signer = Signature.getInstance(
            Signature.ALG_DES_MAC8_ISO9797_1_M2_ALG3, false);
    verifier = Signature.getInstance(
            Signature.ALG_DES_MAC8_ISO9797_1_M2_ALG3, false);
    cipher = Cipher.getInstance(
            Cipher.ALG_DES_CBC_ISO9797_M2, false);
    decipher = Cipher.getInstance(
            Cipher.ALG_DES_CBC_ISO9797_M2, false);
    
    keyMAC = (DESKey) KeyBuilder.buildKey(
            KeyBuilder.TYPE_DES_TRANSIENT_DESELECT, 
            KeyBuilder.LENGTH_DES3_2KEY, false);
    keyENC = (DESKey) KeyBuilder.buildKey(
            KeyBuilder.TYPE_DES_TRANSIENT_DESELECT, 
            KeyBuilder.LENGTH_DES3_2KEY, false);
    
    ssc_set = JCSystem.makeTransientBooleanArray((short)1, JCSystem.CLEAR_ON_DESELECT);
    ssc_set[0] = false;
}
 
开发者ID:jderuiter,项目名称:javacard-openpgpcard,代码行数:28,代码来源:OpenPGPSecureMessaging.java

示例6: setSessionKeys

import javacardx.crypto.Cipher; //导入依赖的package包/类
/**
 * Set the MAC and encryption (and decryption) session keys. Each key is a 
 * 16 byte 3DES EDE key. This method may be called at any time and will 
 * immediately replace the session key.
 * 
 * @param buffer byte array containing the session keys.
 * @param offset location of the session keys in the buffer.
 */
public void setSessionKeys(byte[] buffer, short offset) {
	// Check for empty keys
	if(Util.arrayCompare(buffer, (short)0, EMPTY_KEY, (short)0, KEY_SIZE) == 0 ||
			Util.arrayCompare(buffer, KEY_SIZE, EMPTY_KEY, (short)0, KEY_SIZE) == 0) {
		keyMAC.clearKey();
		keyENC.clearKey();
	}
	else {    	
		keyMAC.setKey(buffer, offset);
		keyENC.setKey(buffer, (short) (offset + KEY_SIZE));
    
		signer.init(keyMAC, Signature.MODE_SIGN);
    	verifier.init(keyMAC, Signature.MODE_VERIFY);
    
    	cipher.init(keyENC, Cipher.MODE_ENCRYPT);
    	decipher.init(keyENC, Cipher.MODE_DECRYPT);
	}
}
 
开发者ID:jderuiter,项目名称:javacard-openpgpcard,代码行数:27,代码来源:OpenPGPSecureMessaging.java

示例7: doFinal

import javacardx.crypto.Cipher; //导入依赖的package包/类
/**
 * Executes the DH function of S = Y^a mod p which is essentially the modexp
 * that is reusable from the modexp (encrypt/decrypt) of RSA. Y is thus
 * taken as a message in terms of RSA.
 *
 * Both Y and S are zeroized after this operation to prevent leaking of
 * security parameters but you might choose to retain the parameters by
 * removing the zeroize function at your own risk.
 *
 * The first 16 bytes (128 bits) of the shared secret is used for a 128 bits
 * AES encryption key. You may derive your HMAC key from S but for
 * simplicity of the demo, we will only encrypt.
 *
 * @param Y
 */
public void doFinal(AESKey encKey) {
    // Set private key into cipher
    dhCipher.init(dhPriv, Cipher.MODE_DECRYPT);

    // Execute S = Y^a mod p via RSA's decrypt
    dhCipher.doFinal(Y, (short) 0, maxLength, S, (short) 0);

    // Set session Encryption key
    encKey.setKey(S, (short) 0);

    // Clear DH Private Key
    dhPriv.clearKey();

    // Zeroize temporary S bytes.
    Utils.zeroize(S);

    // Zeroize temporary Y bytes.
    Utils.zeroize(Y);
}
 
开发者ID:ASKGLab,项目名称:DHApplet,代码行数:35,代码来源:DH.java

示例8: doFinal

import javacardx.crypto.Cipher; //导入依赖的package包/类
/**
 * Executes the DH function of S = Y^a mod p which is essentially the modexp
 * that is reusable from the modexp (encrypt/decrypt) of RSA. Y is thus
 * taken as a message in terms of RSA.
 *
 * Both Y and S are zeroized after this operation to prevent leaking of
 * security parameters but you might choose to retain the parameters by
 * removing the zeroize function at your own risk.
 *
 * The first 32 bytes (256 bits) of the shared secret is used for a 256 bit
 * AES encryption key and the bytes following the first 32 bytes would be
 * used as a HMAC key stored inside an AESKey slot for flexibility of being
 * able to retrieve the AES key bytes for later use.
 *
 * If you don't want to use the default recommendation of the first 32 bytes
 * and following bytes for the derived symmetric keys, you may choose to
 * change them.
 *
 * @param Y
 */
public void doFinal(AESKey encKey, AESKey macKey) {
    // Set private key into cipher
    dhCipher.init(dhPriv, Cipher.MODE_ENCRYPT);

    // Execute S = Y^a mod p via RSA's encrypt
    dhCipher.doFinal(Y, (short) 0, maxLength, S, (short) 0);

    // Set session Encryption key
    encKey.setKey(S, (short) 0);

    // Set session Mac Key
    macKey.setKey(S, (short) 32);

    // Clear DH Private Key
    dhPriv.clearKey();

    // Zeroize temporary S bytes.
    Utils.zeroize(S);

    // Zeroize temporary Y bytes.
    Utils.zeroize(Y);
}
 
开发者ID:ASKGLab,项目名称:DHApplet,代码行数:43,代码来源:DH.java

示例9: authenticateGeneralReplayAttack

import javacardx.crypto.Cipher; //导入依赖的package包/类
@Test
public void authenticateGeneralReplayAttack() {
    byte[] challenge, challengeresponse = new byte[8];
    byte[] key = DatatypeConverter.parseHexBinary("010203040506070801020304050607080102030405060708");
    Cipher cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    DESKey deskey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    deskey.setKey(key, (short) 0);

    // select admin key
    execute("00 22 81 A4 03 83 01 80");
    // get a challenge
    ResponseAPDU response = execute("00 87 00 00 04 7C 02 81 00 00");
    if (!Arrays.equals(Arrays.copyOfRange(response.getBytes(), 0, 4), new byte[] {0x7C,0x0A,(byte) 0x81,0x08})) {
        fail("not a challenge:" + DatatypeConverter.printHexBinary(response.getBytes()));
    }
    // compute the response
    challenge = Arrays.copyOfRange(response.getBytes(), 4, 12);
    //solve challenge
    cipherDES.init(deskey, Cipher.MODE_ENCRYPT);
    cipherDES.doFinal(challenge, (short) 0, (short)8, challengeresponse, (short) 0);
    // send the response
    execute("00 87 00 00 0C 7C 0A 82 08" + DatatypeConverter.printHexBinary(challengeresponse), 0x9000);
    execute("00 87 00 00 0C 7C 0A 82 08" + DatatypeConverter.printHexBinary(challengeresponse), 0x6985);
}
 
开发者ID:vletoux,项目名称:GidsApplet,代码行数:25,代码来源:PinTests.java

示例10: authenticateGeneral

import javacardx.crypto.Cipher; //导入依赖的package包/类
protected void authenticateGeneral(byte[] key, boolean successexpected) {
    byte[] challenge, challengeresponse = new byte[8];
    Cipher cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    DESKey deskey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    deskey.setKey(key, (short) 0);

    // select admin key
    execute("00 22 81 A4 03 83 01 80");
    // get a challenge
    ResponseAPDU response = execute("00 87 00 00 04 7C 02 81 00 00");
    if (!Arrays.equals(Arrays.copyOfRange(response.getBytes(), 0, 4), new byte[] {0x7C,0x0A,(byte) 0x81,0x08})) {
        fail("not a challenge:" + DatatypeConverter.printHexBinary(response.getBytes()));
    }
    // compute the response
    challenge = Arrays.copyOfRange(response.getBytes(), 4, 12);
    //solve challenge
    cipherDES.init(deskey, Cipher.MODE_ENCRYPT);
    cipherDES.doFinal(challenge, (short) 0, (short)8, challengeresponse, (short) 0);
    // send the response
    execute("00 87 00 00 0C 7C 0A 82 08" + DatatypeConverter.printHexBinary(challengeresponse), (successexpected?0x9000: 0x6982));
}
 
开发者ID:vletoux,项目名称:GidsApplet,代码行数:22,代码来源:GidsBaseTestClass.java

示例11: internalAuthenticate

import javacardx.crypto.Cipher; //导入依赖的package包/类
private void internalAuthenticate(APDU apdu) {
  byte[] buffer = apdu.getBuffer();
  // PW1 with 0x82
  if (!pins[PIN_INDEX_PW1].isValidated() || !pinSubmitted[1]) {
    ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
  }
  short len = apdu.setIncomingAndReceive();
  if (len > (short) 102 || len != (buffer[ISO7816.OFFSET_LC] & 0xFF)) {
    ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
  }
  if (!authenticationKey.getPrivate().isInitialized()) {
    ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
  }
  cipherRSA.init(authenticationKey.getPrivate(), Cipher.MODE_ENCRYPT);
  cipherRSA.doFinal(buffer, ISO7816.OFFSET_CDATA, len, buffer, (short) 0);
  apdu.setOutgoingAndSend((short) 0, RSA_KEY_LENGTH_BYTES);
}
 
开发者ID:JavaCardOS,项目名称:FluffyPGP-Applet,代码行数:18,代码来源:Gpg.java

示例12: FIDOStandalone

import javacardx.crypto.Cipher; //导入依赖的package包/类
public FIDOStandalone() {
    scratch = JCSystem.makeTransientByteArray((short)64, JCSystem.CLEAR_ON_DESELECT);
    keyPair = new KeyPair(
        (ECPublicKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PUBLIC, KeyBuilder.LENGTH_EC_FP_256, false),
        (ECPrivateKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false));
    Secp256r1.setCommonCurveParameters((ECKey)keyPair.getPrivate());
    Secp256r1.setCommonCurveParameters((ECKey)keyPair.getPublic());
    random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
    // Initialize the unique wrapping key
    chipKey = (AESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_256, false);
    random.generateData(scratch, (short)0, (short)32);
    chipKey.setKey(scratch, (short)0);
    cipherEncrypt = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
    cipherEncrypt.init(chipKey, Cipher.MODE_ENCRYPT, IV_ZERO_AES, (short)0, (short)IV_ZERO_AES.length);
    cipherDecrypt = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
    cipherDecrypt.init(chipKey, Cipher.MODE_DECRYPT, IV_ZERO_AES, (short)0, (short)IV_ZERO_AES.length);
}
 
开发者ID:LedgerHQ,项目名称:ledger-u2f-javacard,代码行数:18,代码来源:FIDOStandalone.java

示例13: decryptWithCardKey

import javacardx.crypto.Cipher; //导入依赖的package包/类
private boolean decryptWithCardKey(byte[] input, short offset, byte[] output)
{
	if(!card_cipher_initialised) {
		RSAPrivateCrtKey private_key = (RSAPrivateCrtKey)card_key.getPrivate();
		card_cipher.init(private_key, Cipher.MODE_DECRYPT);

		card_cipher_initialised = true;
	}

	card_cipher.doFinal(input, offset, (short)(RSA_KEYLENGTH / 8), output, (short)0);
	return true;
}
 
开发者ID:nfd,项目名称:smartcard_crypto_applet,代码行数:13,代码来源:KeepassNFC.java

示例14: setSessionKeyEncryption

import javacardx.crypto.Cipher; //导入依赖的package包/类
/**
 * Set the encryption session key. Each key is a 16 byte 3DES EDE key. This method 
 * may be called at any time and will immediately replace the session key.
 * 
 * @param buffer byte array containing the session key.
 * @param offset location of the session key in the buffer.
 */
public void setSessionKeyEncryption(byte[] buffer, short offset) {
	// Check for empty keys
	if(Util.arrayCompare(buffer, (short)0, EMPTY_KEY, (short)0, KEY_SIZE) == 0) {
		keyMAC.clearKey();
		keyENC.clearKey();
	}
	else {     	
		keyENC.setKey(buffer, (short) (offset + KEY_SIZE));
    
		cipher.init(keyENC, Cipher.MODE_ENCRYPT);
		decipher.init(keyENC, Cipher.MODE_DECRYPT);
	}
}
 
开发者ID:jderuiter,项目名称:javacard-openpgpcard,代码行数:21,代码来源:OpenPGPSecureMessaging.java

示例15: DH

import javacardx.crypto.Cipher; //导入依赖的package包/类
public DH() {
    // Creates a RSA private key instance as template for the DH private key
    dhPriv = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE_TRANSIENT_RESET, KeyBuilder.LENGTH_RSA_2048, false);

    // Creates an RSA cipher instance
    dhCipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);

    // Set default G to 2
    G[(short) (maxLength - 1)] = (byte) 0x02;
}
 
开发者ID:ASKGLab,项目名称:DHApplet,代码行数:11,代码来源:DH.java


注:本文中的javacardx.crypto.Cipher类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。