本文整理汇总了Java中java.security.SecureRandom类的典型用法代码示例。如果您正苦于以下问题:Java SecureRandom类的具体用法?Java SecureRandom怎么用?Java SecureRandom使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SecureRandom类属于java.security包,在下文中一共展示了SecureRandom类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: generate
import java.security.SecureRandom; //导入依赖的package包/类
public X509Certificate generate(String dn, KeyPair keyPair) throws CertificateException {
try {
Security.addProvider(new BouncyCastleProvider());
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
X500Name name = new X500Name(dn);
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000L);
BigInteger sn = new BigInteger(64, new SecureRandom());
X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
if (subjectAltName != null)
v3CertGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
} catch (CertificateException ce) {
throw ce;
} catch (Exception e) {
throw new CertificateException(e);
}
}
示例2: ECKey
import java.security.SecureRandom; //导入依赖的package包/类
/**
* Generate a new keypair using the given Java Security Provider.
*
* All private key operations will use the provider.
*/
public ECKey(Provider provider, SecureRandom secureRandom) {
this.provider = provider;
final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
final KeyPair keyPair = keyPairGen.generateKeyPair();
this.privKey = keyPair.getPrivate();
final PublicKey pubKey = keyPair.getPublic();
if (pubKey instanceof BCECPublicKey) {
pub = ((BCECPublicKey) pubKey).getQ();
} else if (pubKey instanceof ECPublicKey) {
pub = extractPublicKey((ECPublicKey) pubKey);
} else {
throw new AssertionError(
"Expected Provider " + provider.getName() +
" to produce a subtype of ECPublicKey, found " + pubKey.getClass());
}
}
示例3: ECKey
import java.security.SecureRandom; //导入依赖的package包/类
/**
* Generate a new keypair using the given Java Security Provider.
*
* All private key operations will use the provider.
*/
public ECKey(Provider provider, SecureRandom secureRandom) {
this.provider = provider;
final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
final KeyPair keyPair = keyPairGen.generateKeyPair();
this.privKey = keyPair.getPrivate();
final PublicKey pubKey = keyPair.getPublic();
if (pubKey instanceof BCECPublicKey) {
pub = ((BCECPublicKey) pubKey).getQ();
} else if (pubKey instanceof ECPublicKey) {
pub = extractPublicKey((ECPublicKey) pubKey);
} else {
throw new AssertionError(
"Expected Provider " + provider.getName() +
" to produce a subtype of ECPublicKey, found " + pubKey.getClass());
}
}
示例4: SslContextProvider
import java.security.SecureRandom; //导入依赖的package包/类
private SslContextProvider() {
// load SSL context
TrustManager[] trustManager = new TrustManager[]{X509TrustManagerFactory.getInstance()};
try {
this.sslContext = SSLContext.getInstance("TLSv1.2");
this.sslContext.init(null, trustManager, new SecureRandom());
// disable SSL session caching - we load SSL certificates dinamically so we need to ensure
// that we have up to date cached certificates list
this.sslContext.getClientSessionContext().setSessionCacheSize(1);
this.sslContext.getClientSessionContext().setSessionTimeout(1);
this.sslContext.getServerSessionContext().setSessionCacheSize(1);
this.sslContext.getServerSessionContext().setSessionTimeout(1);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
LOG.error("Encountering security exception in SSL context", e);
throw new RuntimeException("Internal error with SSL context", e);
}
}
示例5: enableTLSConnectionManager
import java.security.SecureRandom; //导入依赖的package包/类
private static ClientConnectionManager enableTLSConnectionManager() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, new SecureRandom());
Logger.debug(LOG_TAG, "Using protocols and cipher suites for Android API " + android.os.Build.VERSION.SDK_INT);
SSLSocketFactory sf = new SSLSocketFactory(sslContext, GlobalConstants.DEFAULT_PROTOCOLS, GlobalConstants.DEFAULT_CIPHER_SUITES, null);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", 443, sf));
schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
connManager = cm;
return cm;
}
示例6: encrypt
import java.security.SecureRandom; //导入依赖的package包/类
/**
* DES加密
*
* @author : chenssy
* @date : 2016年5月20日 下午5:51:37
*
* @param data
* 待加密字符串
* @param key
* 校验位
* @return
*/
@SuppressWarnings("restriction")
protected static String encrypt(String data,String key) {
String encryptedData = null;
try {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(key.getBytes());
// 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(deskey);
// 加密对象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
// 加密,并把字节数组编码成字符串
encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
} catch (Exception e) {
throw new RuntimeException("加密错误,错误信息:", e);
}
return encryptedData;
}
示例7: withBindHolder
import java.security.SecureRandom; //导入依赖的package包/类
@Override
protected void withBindHolder(itemCommonBinder holder, String data, int position) {
holder.textViewSample.setText(data + "just the sample data");
holder.item_view.setBackgroundColor(Color.parseColor("#AAffffff"));
SecureRandom imgGen = new SecureRandom();
switch (imgGen.nextInt(3)) {
case 0:
holder.imageViewSample.setImageResource(R.drawable.scn1);
break;
case 1:
holder.imageViewSample.setImageResource(R.drawable.jr13);
break;
case 2:
holder.imageViewSample.setImageResource(R.drawable.jr16);
break;
}
}
示例8: marry
import java.security.SecureRandom; //导入依赖的package包/类
private static void marry() {
if (!options.has(xpubkeysFlag)) {
throw new IllegalStateException();
}
String[] xpubkeys = options.valueOf(xpubkeysFlag).split(",");
ImmutableList.Builder<DeterministicKey> keys = ImmutableList.builder();
for (String xpubkey : xpubkeys) {
keys.add(DeterministicKey.deserializeB58(null, xpubkey.trim(), params));
}
MarriedKeyChain chain = MarriedKeyChain.builder()
.random(new SecureRandom())
.followingKeys(keys.build())
.build();
wallet.addAndActivateHDChain(chain);
}
示例9: createSecureRandom
import java.security.SecureRandom; //导入依赖的package包/类
private static SecureRandom createSecureRandom()
{
/*
* We use our threaded seed generator to generate a good random seed. If the user has a
* better random seed, he should use the constructor with a SecureRandom.
*/
ThreadedSeedGenerator tsg = new ThreadedSeedGenerator();
SecureRandom random = new SecureRandom();
/*
* Hopefully, 20 bytes in fast mode are good enough.
*/
random.setSeed(tsg.generateSeed(20, true));
return random;
}
示例10: EncryptionPayload
import java.security.SecureRandom; //导入依赖的package包/类
@JsonCreator
public EncryptionPayload(@JsonProperty("value") SecretValue value,
@JsonProperty("userdata") Optional<UserData> userData,
@JsonProperty("created") ZonedDateTime created,
Optional<UserAlias> createdBy,
@JsonProperty("modified") ZonedDateTime modified,
Optional<UserAlias> modifiedBy,
@JsonProperty("comment") Optional<Comment> comment) {
this.value = value;
this.userData = userData;
this.created = created;
this.modified = modified;
this.createdBy = createdBy;
this.modifiedBy = modifiedBy;
this.comment = comment;
try {
this.random = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to instantiate random number generator", e);
}
}
示例11: init
import java.security.SecureRandom; //导入依赖的package包/类
public void init(
boolean forSigning,
CipherParameters param)
{
this.forSigning = forSigning;
if (forSigning)
{
if (param instanceof ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)param;
this.random = rParam.getRandom();
this.key = (ECPrivateKeyParameters)rParam.getParameters();
}
else
{
this.random = new SecureRandom();
this.key = (ECPrivateKeyParameters)param;
}
}
else
{
this.key = (ECPublicKeyParameters)param;
}
}
示例12: initialize
import java.security.SecureRandom; //导入依赖的package包/类
public void initialize(
int strength,
SecureRandom random)
{
this.random = random;
if (ecParams != null)
{
try
{
initialize((ECGenParameterSpec)ecParams, random);
}
catch (InvalidAlgorithmParameterException e)
{
throw new InvalidParameterException("key size not configurable.");
}
}
else
{
throw new InvalidParameterException("unknown key size.");
}
}
示例13: initialize
import java.security.SecureRandom; //导入依赖的package包/类
public void initialize(
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (!(params instanceof DHParameterSpec))
{
throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec");
}
DHParameterSpec dhParams = (DHParameterSpec)params;
param = new DHKeyGenerationParameters(random, new DHParameters(dhParams.getP(), dhParams.getG(), null, dhParams.getL()));
engine.init(param);
initialised = true;
}
示例14: engineInit
import java.security.SecureRandom; //导入依赖的package包/类
public void engineInit(
int opmode,
Key key,
AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
AlgorithmParameterSpec paramSpec = null;
if (params != null)
{
try
{
paramSpec = params.getParameterSpec(IESParameterSpec.class);
}
catch (Exception e)
{
throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString());
}
}
engineParam = params;
engineInit(opmode, key, paramSpec, random);
}
示例15: NTRUEncryptionKeyGenerationParameters
import java.security.SecureRandom; //导入依赖的package包/类
/**
* Constructs a parameter set that uses ternary private keys (i.e. </code>polyType=SIMPLE</code>).
*
* @param N number of polynomial coefficients
* @param q modulus
* @param df number of ones in the private polynomial <code>f</code>
* @param dm0 minimum acceptable number of -1's, 0's, and 1's in the polynomial <code>m'</code> in the last encryption step
* @param db number of random bits to prepend to the message
* @param c a parameter for the Index Generation Function ({@link org.bouncycastle.pqc.crypto.ntru.IndexGenerator})
* @param minCallsR minimum number of hash calls for the IGF to make
* @param minCallsMask minimum number of calls to generate the masking polynomial
* @param hashSeed whether to hash the seed in the MGF first (true) or use the seed directly (false)
* @param oid three bytes that uniquely identify the parameter set
* @param sparse whether to treat ternary polynomials as sparsely populated ({@link org.bouncycastle.pqc.math.ntru.polynomial.SparseTernaryPolynomial} vs {@link org.bouncycastle.pqc.math.ntru.polynomial.DenseTernaryPolynomial})
* @param fastFp whether <code>f=1+p*F</code> for a ternary <code>F</code> (true) or <code>f</code> is ternary (false)
* @param hashAlg a valid identifier for a <code>java.security.MessageDigest</code> instance such as <code>SHA-256</code>. The <code>MessageDigest</code> must support the <code>getDigestLength()</code> method.
*/
public NTRUEncryptionKeyGenerationParameters(int N, int q, int df, int dm0, int db, int c, int minCallsR, int minCallsMask, boolean hashSeed, byte[] oid, boolean sparse, boolean fastFp, Digest hashAlg)
{
super(new SecureRandom(), db);
this.N = N;
this.q = q;
this.df = df;
this.db = db;
this.dm0 = dm0;
this.c = c;
this.minCallsR = minCallsR;
this.minCallsMask = minCallsMask;
this.hashSeed = hashSeed;
this.oid = oid;
this.sparse = sparse;
this.fastFp = fastFp;
this.polyType = NTRUParameters.TERNARY_POLYNOMIAL_TYPE_SIMPLE;
this.hashAlg = hashAlg;
init();
}