當前位置: 首頁>>代碼示例>>Java>>正文


Java GCMParameterSpec類代碼示例

本文整理匯總了Java中javax.crypto.spec.GCMParameterSpec的典型用法代碼示例。如果您正苦於以下問題:Java GCMParameterSpec類的具體用法?Java GCMParameterSpec怎麽用?Java GCMParameterSpec使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


GCMParameterSpec類屬於javax.crypto.spec包,在下文中一共展示了GCMParameterSpec類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: newGCMParameterSpecPass

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
private static void newGCMParameterSpecPass(
        int tLen, byte[] src, int offset, int len) {
    try {
        GCMParameterSpec gcmps =
            new GCMParameterSpec(tLen, src, offset, len);
        if (gcmps.getTLen() != tLen) {
            throw new Exception("tLen's not equal");
        }
        if (!Arrays.equals(gcmps.getIV(),
                Arrays.copyOfRange(src, offset, offset + len))) {
            System.out.println(offset + " " + len);
            System.out.println(Arrays.copyOfRange(src, offset, len)[0]);
            throw new Exception("IV's not equal");
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed++;
    }
}
 
開發者ID:JetBrains,項目名稱:jdk8u_jdk,代碼行數:20,代碼來源:GCMParameterSpecTest.java

示例2: decrypt

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
public String decrypt(final String alias, final byte[] encryptedData, Context appContext)
        throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException,
        NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {

    final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    String IV = PreferenceHelper.getPrefernceHelperInstace().getString(appContext, "IV", "");

    if (null != IV && !IV.isEmpty()) {
        byte[] encryptionIv = Base64.decode(IV, Base64.DEFAULT);
        Log.e("Decrypter", "IV : " + IV + " IV size " + encryptionIv.length);
        final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec);
        return new String(cipher.doFinal(encryptedData), "UTF-8");
    } else {
        return "{}";
    }
}
 
開發者ID:hiteshsahu,項目名稱:FingerPrint-Authentication-With-React-Native-Android,代碼行數:19,代碼來源:Decrypter.java

示例3: isAvailable

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
Boolean isAvailable() {
    // We won't know whether a cipher for a particular key size is
    // available until the cipher is successfully initialized.
    //
    // We do not initialize AEAD cipher in the constructor.  Need to
    // initialize the cipher to ensure that the AEAD mode for a
    // particular key size is supported.
    if (cipherType == AEAD_CIPHER) {
        try {
            Authenticator authenticator =
                new Authenticator(protocolVersion);
            byte[] nonce = authenticator.sequenceNumber();
            byte[] iv = Arrays.copyOf(fixedIv,
                                        fixedIv.length + nonce.length);
            System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length);
            GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);

            cipher.init(mode, key, spec, random);
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }   // Otherwise, we have initialized the cipher in the constructor.

    return Boolean.TRUE;
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:26,代碼來源:CipherBox.java

示例4: getCipherTextBySpec

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
private byte[] getCipherTextBySpec(GCMParameterSpec spec) throws Exception {
    // init a cipher
    Cipher cipher = createCipher(Cipher.ENCRYPT_MODE, spec);
    cipher.updateAAD(AAD);
    byte[] cipherText = cipher.doFinal(data);

    // check IVs
    if (!Arrays.equals(cipher.getIV(), spec.getIV())) {
        System.out.println("IV in parameters is incorrect");
        return null;
    }
    if (spec.getTLen() != (cipherText.length - data.length) * 8) {
        System.out.println("Tag length is incorrect");
        return null;
    }
    return cipherText;
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:18,代碼來源:GCMParameterSpecTest.java

示例5: doTestWithSeparateArrays

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
private void doTestWithSeparateArrays(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare buffers to test
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset * 2;

    byte[] inputText = Helper.generateBytes(outputBufSize);
    byte[] AAD = Helper.generateBytes(AADLength);

    // do the test
    runGCMWithSeparateArray(Cipher.ENCRYPT_MODE, AAD, inputText, offset * 2,
            textLength, offset, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    runGCMWithSeparateArray(Cipher.DECRYPT_MODE, AAD, inputText, offset,
            textLength + tagLength, offset, params);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:19,代碼來源:SameBuffer.java

示例6: doTestWithSameArrays

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
/**
 * Run the test in case when AAD and text are placed in the same byte
 * array.
 */
private void doTestWithSameArrays(int offset, AlgorithmParameters params)
        throws Exception {
    // prepare buffers to test
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = AADLength + outputLength + offset * 2;

    byte[] AAD_and_text = Helper.generateBytes(outputBufSize);

    // do the test
    runGCMWithSameArray(Cipher.ENCRYPT_MODE, AAD_and_text, AADLength + offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    runGCMWithSameArray(Cipher.DECRYPT_MODE, AAD_and_text, AADLength + offset,
            textLength + tagLength, params);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:22,代碼來源:SameBuffer.java

示例7: doTestWithSameBuffer

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
private void doTestWithSameBuffer(int offset, AlgorithmParameters params)
        throws Exception {
    // calculate output length
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);

    // prepare byte buffer contained AAD and plain text
    int bufSize = AADLength + offset + outputLength;
    byte[] AAD_and_Text = Helper.generateBytes(bufSize);
    ByteBuffer AAD_and_Text_Buf = ByteBuffer.allocate(bufSize);
    AAD_and_Text_Buf.put(AAD_and_Text, 0, AAD_and_Text.length);

    // do test
    runGCMWithSameBuffer(Cipher.ENCRYPT_MODE, AAD_and_Text_Buf, offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    AAD_and_Text_Buf.limit(AADLength + offset + textLength + tagLength);
    runGCMWithSameBuffer(Cipher.DECRYPT_MODE, AAD_and_Text_Buf, offset,
            textLength + tagLength, params);

}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:23,代碼來源:SameBuffer.java

示例8: engineGetParameters

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
@Override
protected synchronized AlgorithmParameters engineGetParameters() {
    AlgorithmParameters params = null;
    try {
        if (iv != null) {
            GCMParameterSpec gcmSpec = new GCMParameterSpec(tagLen, iv.clone());
            params = AlgorithmParameters.getInstance("GCM");
            params.init(gcmSpec);
        }
    } catch (GeneralSecurityException e) {
        // NoSuchAlgorithmException, NoSuchProviderException
        // InvalidParameterSpecException
        throw new UcryptoException("Could not encode parameters", e);
    }
    return params;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:NativeGCMCipher.java

示例9: encryptString

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
public static String encryptString(String password, String value) {
    String salt = KeyGenerators.string().generateKey();
    SecretKeySpec skeySpec = makeKeySpec(password, salt);
    byte[] iv = KeyGenerators.secureRandom(16).generateKey();
    String ivString = Hex.encodeHexString(iv);

    try {
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
                new GCMParameterSpec(128, iv));
                /*
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
                new IvParameterSpec(iv));
                */

        byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8")));
        String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase();
        // Strip line breaks
        s = salt + ivString + s.replaceAll("(\\n|\\r)", "");
        return s;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:StallionCMS,項目名稱:stallion-core,代碼行數:26,代碼來源:Encrypter.java

示例10: encryptTLS12

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
private EncryptionResult encryptTLS12(EncryptionRequest request) {
    try {
        byte[] nonce = ArrayConverter.longToBytes(context.getWriteSequenceNumber(),
                RecordByteLength.SEQUENCE_NUMBER);
        byte[] iv = ArrayConverter.concatenate(
                getKeySet().getWriteIv(context.getConnection().getLocalConnectionEndType()), nonce);
        encryptIV = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        LOGGER.debug("Encrypting GCM with the following IV: {}", ArrayConverter.bytesToHexString(encryptIV.getIV()));
        encryptCipher.init(Cipher.ENCRYPT_MODE, encryptKey, encryptIV);
        LOGGER.debug("Encrypting GCM with the following AAD: {}",
                ArrayConverter.bytesToHexString(additionalAuthenticatedData));
        encryptCipher.updateAAD(additionalAuthenticatedData);
        byte[] ciphertext = encryptCipher.doFinal(request.getPlainText());
        return new EncryptionResult(encryptIV.getIV(), ArrayConverter.concatenate(nonce, ciphertext), false);
    } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | InvalidAlgorithmParameterException ex) {
        throw new CryptoException(ex);
    }
}
 
開發者ID:RUB-NDS,項目名稱:TLS-Attacker,代碼行數:20,代碼來源:RecordAEADCipher.java

示例11: decryptTLS12

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
private byte[] decryptTLS12(byte[] data) {
    try {
        byte[] nonce = Arrays.copyOf(data, SEQUENCE_NUMBER_LENGTH);
        data = Arrays.copyOfRange(data, SEQUENCE_NUMBER_LENGTH, data.length);
        byte[] iv = ArrayConverter.concatenate(
                getKeySet().getReadIv(context.getConnection().getLocalConnectionEndType()), nonce);
        decryptIV = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        LOGGER.debug("Decrypting GCM with the following IV: {}", ArrayConverter.bytesToHexString(decryptIV.getIV()));
        decryptCipher.init(Cipher.DECRYPT_MODE, decryptKey, decryptIV);
        LOGGER.debug("Decrypting GCM with the following AAD: {}",
                ArrayConverter.bytesToHexString(additionalAuthenticatedData));
        decryptCipher.updateAAD(additionalAuthenticatedData);
        LOGGER.debug("Decrypting the following GCM ciphertext: {}", ArrayConverter.bytesToHexString(data));
        return decryptCipher.doFinal(data);
    } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | InvalidAlgorithmParameterException ex) {
        throw new CryptoException(ex);
    }
}
 
開發者ID:RUB-NDS,項目名稱:TLS-Attacker,代碼行數:20,代碼來源:RecordAEADCipher.java

示例12: GcmTestVector

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
public GcmTestVector(
    String message,
    String keyMaterial,
    String nonce,
    String aad,
    String ciphertext,
    String tag) {
  this.ptHex = message;
  this.pt = TestUtil.hexToBytes(message);
  this.aad = TestUtil.hexToBytes(aad);
  this.ct = TestUtil.hexToBytes(ciphertext + tag);
  this.ctHex = ciphertext + tag;
  this.tagLengthInBits = 4 * tag.length();
  this.nonceLengthInBits = 4 * nonce.length();
  this.parameters = new GCMParameterSpec(tagLengthInBits, TestUtil.hexToBytes(nonce));
  this.key = new SecretKeySpec(TestUtil.hexToBytes(keyMaterial), "AES");
}
 
開發者ID:google,項目名稱:wycheproof,代碼行數:18,代碼來源:AesGcmTest.java

示例13: decrypt

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
byte[] decrypt(byte[] message) throws Exception {
	if(message==null || message.length < GCM_NONCE_LENGTH + GCM_TAG_LENGTH) {			// needs room for message + IV + authentication tag
		if(optionalDecrypt) {
			CTinfo.debugPrint("Warning: Decrypt failed, returning raw data");
			return message;					// quietly fail
		}
		else 	throw new IllegalArgumentException();
	}		

	Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");	
	GCMParameterSpec params = new GCMParameterSpec(8*GCM_TAG_LENGTH, message, 0, GCM_NONCE_LENGTH);

	cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
	try {
		return cipher.doFinal(message, GCM_NONCE_LENGTH, message.length - GCM_NONCE_LENGTH);	// skip IV at start
	}
	catch(Exception e) {
		if(optionalDecrypt) {
			CTinfo.debugPrint("Warning: decrypt failed, returning raw data");
			return message;
		}
		else throw e;
	}
}
 
開發者ID:cycronix,項目名稱:cloudturbine,代碼行數:25,代碼來源:CTcrypto.java

示例14: decryptCurrentKeystoreVersion

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
@NonNull
private String decryptCurrentKeystoreVersion(String encryptedData) throws KeyStoreException {
    try {
        final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), spec);

        final byte[] encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT);
        final byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, UTF_8);
    } catch (UnrecoverableEntryException | UnsupportedEncodingException
            | IllegalBlockSizeException | NoSuchPaddingException
            | InvalidAlgorithmParameterException | InvalidKeyException | java.security.KeyStoreException
            | BadPaddingException | NoSuchAlgorithmException e) {
        throw new KeyStoreException(new Throwable(e.getMessage()));
    }
}
 
開發者ID:toshiapp,項目名稱:toshi-android-client,代碼行數:18,代碼來源:KeystoreHandler23.java

示例15: encrypt

import javax.crypto.spec.GCMParameterSpec; //導入依賴的package包/類
@Override
public byte[] encrypt(byte[] rawEncryptionKey, byte[] rawData, @Nullable byte[] associatedData) throws AuthenticatedEncryptionException {
    if (rawEncryptionKey.length < 16) {
        throw new IllegalArgumentException("key length must be longer than 16 byte");
    }

    try {
        byte[] iv = new byte[IV_LENGTH_BYTE];
        secureRandom.nextBytes(iv);

        final Cipher cipher = getCipher();
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(rawEncryptionKey, "AES"), new GCMParameterSpec(TAG_LENGTH_BIT, iv));

        if (associatedData != null) {
            cipher.updateAAD(associatedData);
        }

        byte[] encrypted = cipher.doFinal(rawData);

        ByteBuffer byteBuffer = ByteBuffer.allocate(1 + iv.length + encrypted.length);
        byteBuffer.put((byte) iv.length);
        byteBuffer.put(iv);
        byteBuffer.put(encrypted);
        return byteBuffer.array();
    } catch (Exception e) {
        throw new AuthenticatedEncryptionException("could not encrypt", e);
    }
}
 
開發者ID:patrickfav,項目名稱:armadillo,代碼行數:29,代碼來源:AesGcmEncryption.java


注:本文中的javax.crypto.spec.GCMParameterSpec類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。