List of usage examples for java.security.interfaces RSAPublicKey getModulus
public BigInteger getModulus();
From source file:be.e_contract.mycarenet.common.SessionKey.java
/** * Gives back the RSA modulus./*from w ww .java 2 s. co m*/ * * @return */ public byte[] getModulus() { RSAPublicKey rsaPublicKey = getRSAPublicKey(); return rsaPublicKey.getModulus().toByteArray(); }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testManualEncryption() throws Exception { while (true) { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); SecureRandom random = new SecureRandom(); int keySize = 128; keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; LOG.debug("private key modulus: " + rsaPrivateKey.getModulus()); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; LOG.debug("public key modulus: " + rsaPublicKey.getModulus()); LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent()); LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); int dataSize = keySize / 8 - 11; byte[] data1 = new byte[dataSize]; for (int i = 0; i < data1.length; i++) { data1[i] = 0x00;//from ww w . j a v a 2s . c o m } byte[] data2 = new byte[dataSize]; for (int i = 0; i < data2.length; i++) { data2[i] = 0x00; } data2[data2.length - 1] = 0x07; byte[] signatureValue1 = cipher.doFinal(data1); LOG.debug("signature size: " + signatureValue1.length); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] signatureValue2 = cipher.doFinal(data2); BigInteger sigBigInt1 = new BigInteger(signatureValue1); BigInteger sigBigInt2 = new BigInteger(signatureValue2); BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("msg big int: " + msgBigInt1); byte[] msgBytes1 = msgBigInt1.toByteArray(); LOG.debug("original message size: " + msgBytes1.length); LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1))); LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray()))); LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100)); LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100)); // BigInteger.pow offers a very naive implementation LOG.debug("calculating s1^e..."); BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s1^e: " + s1_e); LOG.debug("calculating s2^e..."); BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s2^e: " + s2_e); LOG.debug("calculating GCD..."); LOG.debug("msg1: " + msgBigInt1); LOG.debug("msg2: " + msgBigInt2); BigInteger a = s1_e.subtract(msgBigInt1); BigInteger b = s2_e.subtract(msgBigInt2); LOG.debug("a: " + a); LOG.debug("b: " + b); BigInteger candidateModulus = a.gcd(b); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length); BigInteger s_e = s1_e.multiply(s2_e); BigInteger m = msgBigInt1.multiply(msgBigInt2); while (false == rsaPublicKey.getModulus().equals(candidateModulus)) { LOG.error("incorrect candidate modulus"); LOG.debug("modulus | candidate modulus: " + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO)); s_e = s_e.multiply(s1_e); m = m.multiply(msgBigInt1); BigInteger n1 = s_e.subtract(m).gcd(a); BigInteger n2 = s_e.subtract(m).gcd(b); candidateModulus = n1.gcd(n2); // try / 2 LOG.debug("new modulus: " + n1); LOG.debug("new modulus: " + n2); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("actual mod: " + rsaPublicKey.getModulus()); } } }
From source file:com.hyeb.back.login.LoginController.java
/** * //from www.j av a 2 s .c o m */ @RequestMapping(value = "/login") public String login(ModelMap model, RedirectAttributes redirectAttributes, HttpServletRequest request) { /** "?"??? */ final String PRIVATE_KEY_ATTRIBUTE_NAME = "privateKey"; //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); Setting setting = SettingUtils.get(); KeyPair keyPair = RSAUtils.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); request.getSession().setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey); String modulus = Base64.encodeBase64String(publicKey.getModulus().toByteArray());//N String exponent = Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray());//e String captchaId = UUID.randomUUID().toString(); boolean isBackCaptcha = ArrayUtils.contains(setting.getCaptchaTypes(), CaptchaType.adminLogin); model.addAttribute("modulus", modulus); model.addAttribute("exponent", exponent); model.addAttribute("captchaId", captchaId); model.addAttribute("isBackCaptcha", isBackCaptcha); String messageStr = null; String loginFailure = (String) request .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (loginFailure != null) { if (loginFailure.equals("org.apache.shiro.authc.pam.UnsupportedTokenException")) {//?? messageStr = "admin.captcha.invalid"; } else if (loginFailure.equals("org.apache.shiro.authc.UnknownAccountException")) {// messageStr = "admin.login.unknownAccount"; } else if (loginFailure.equals("org.apache.shiro.authc.DisabledAccountException")) {//? messageStr = "admin.login.disabledAccount";// } else if (loginFailure.equals("org.apache.shiro.authc.LockedAccountException")) {//? messageStr = "admin.login.lockedAccount"; } else if (loginFailure.equals("org.apache.shiro.authc.IncorrectCredentialsException")) {//?? if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.admin)) { messageStr = "admin.login.accountLockCount";//?{0}??? } else { messageStr = "admin.login.incorrectCredentials";//??? } } else if (loginFailure.equals("org.apache.shiro.authc.AuthenticationException")) {// messageStr = "admin.login.authentication";//?? } if (messageStr != null) { Message message = Message.warn(messageStr); addFlashMessage(redirectAttributes, message); } } Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { return "redirect:/back/main/main"; } else { return "/back/login/login"; } }
From source file:test.be.fedict.eid.applet.PKCS11Test.java
@Test public void testPKCS1viaPKCS11() throws Exception { File tmpConfigFile = File.createTempFile("pkcs11-", "conf"); tmpConfigFile.deleteOnExit();/*from w w w.j a v a2s . c o m*/ PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true); configWriter.println("name=SmartCard"); configWriter.println("library=/usr/lib/libbeidpkcs11.so.0"); configWriter.println("slotListIndex=2"); SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(provider); KeyStore keyStore = KeyStore.getInstance("PKCS11", provider); keyStore.load(null, null); PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null); PrivateKey privateKey = privateKeyEntry.getPrivateKey(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate(); RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey(); BigInteger signatureValueBigInteger = new BigInteger(signatureValue); BigInteger messageBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(), publicKey.getModulus()); LOG.debug("original message: " + new String(Hex.encodeHex(messageBigInteger.toByteArray()))); // LOG.debug("ASN.1 signature: " + ASN1Dump.dumpAsString(obj) }
From source file:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java
@Test public void testSignature() throws Exception { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test"); EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();//from w ww . ja va 2 s . c om KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12, KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret"); entityManager.persist(keyStoreEntity); KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean(); Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager"); entityManagerField.setAccessible(true); entityManagerField.set(keyStoreSingletonBean, entityManager); KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean(); Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader"); keyStoreLoaderField.setAccessible(true); keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean); keyStoreSingletonBean.loadKeys(); keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId()); byte[] toBeSigned = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(toBeSigned); byte[] digestValue = messageDigest.digest(); LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue))); byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue); assertNotNull(signatureValue); LOG.debug("signature size: " + signatureValue.length); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray()); RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey(); BigInteger signatureValueBigInteger = new BigInteger(signatureValue); BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(), publicKey.getModulus()); LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray()))); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(publicKey); signature.update(toBeSigned); boolean result = signature.verify(signatureValue); assertTrue(result); }
From source file:fr.cls.atoll.motu.library.misc.vfs.provider.gsiftp.ProxyTool.java
/** * Verify.//from www. ja va 2 s. c o m * * @throws GeneralSecurityException the general security exception */ private void verify() throws GeneralSecurityException { RSAPublicKey pkey = (RSAPublicKey) this.certificates[0].getPublicKey(); RSAPrivateKey prkey = (RSAPrivateKey) userKey; if (!pkey.getModulus().equals(prkey.getModulus())) { throw new GeneralSecurityException("Certificate and private key specified do not match"); } }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.certificate.DefaultJSONSigner.java
@Override public String sign(KeyPair keyPair, JSONObject json) throws Exception { if (keyPair == null || json == null) { throw new IllegalArgumentException("parameter cannot be null"); }/*from w w w . j a v a 2s .c om*/ RSAPublicKey publicKey = ((RSAPublicKey) keyPair.getPublic()); PrivateKey privateKey = keyPair.getPrivate(); // create CSR Header (based on public key) JSONObject jwsHeaderJson = new JSONObject(); jwsHeaderJson.put(ALG, "RS256"); JSONObject publicKeyDataJson = new JSONObject(); publicKeyDataJson.put(ALG, "RSA"); String mod = encodeUrlSafe(publicKey.getModulus().toByteArray()); publicKeyDataJson.put("mod", mod); String exp = encodeUrlSafe(publicKey.getPublicExponent().toByteArray()); publicKeyDataJson.put("exp", exp); jwsHeaderJson.put("jpk", publicKeyDataJson); String jwsHeader = jwsHeaderJson.toString(); String payload = json.toString(); // concatenate JWS Header and payload. String csrHeaderAndPayload = encodeUrlSafe(jwsHeader.getBytes()) + "." + encodeUrlSafe(payload.getBytes()); // create CSR Signature String jwsSignature = encodeUrlSafe(signCsrData(csrHeaderAndPayload, privateKey)); // Concatenate them all, and return the result. return csrHeaderAndPayload + "." + jwsSignature; }
From source file:org.keycloak.jose.jwk.JWKBuilder.java
public JWK rsa(Key key, X509Certificate certificate) { RSAPublicKey rsaKey = (RSAPublicKey) key; RSAPublicJWK k = new RSAPublicJWK(); String kid = this.kid != null ? this.kid : KeyUtils.createKeyId(key); k.setKeyId(kid);// w ww .ja va2 s . c om k.setKeyType(KeyType.RSA); k.setAlgorithm(algorithm); k.setPublicKeyUse(DEFAULT_PUBLIC_KEY_USE); k.setModulus(Base64Url.encode(toIntegerBytes(rsaKey.getModulus()))); k.setPublicExponent(Base64Url.encode(toIntegerBytes(rsaKey.getPublicExponent()))); if (certificate != null) { k.setX509CertificateChain(new String[] { PemUtils.encodeCertificate(certificate) }); } return k; }
From source file:com.hyeb.front.controller.CommonController.java
/** * /* w ww . j a va 2s. com*/ */ @RequestMapping(value = "/public_key", method = RequestMethod.GET) public @ResponseBody Map<String, String> publicKey(HttpServletRequest request) { Assert.notNull(request); KeyPair keyPair = RSAUtils.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); HttpSession session = request.getSession(); session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey); Map<String, String> data = new HashMap<String, String>(); data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray())); data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray())); return data; }
From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
@Override public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception { KeyPairGenerator keyGen = null; if (signatureAlgorithm == null) { throw new RuntimeException("The signature algorithm parameter cannot be null"); } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) { keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC"); keyGen.initialize(2048, new SecureRandom()); } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) { ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()); keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC"); keyGen.initialize(eccgen, new SecureRandom()); } else {/*from ww w . j a v a 2 s . c o m*/ throw new RuntimeException("The provided signature algorithm parameter is not supported"); } // Generate the key KeyPair keyPair = keyGen.generateKeyPair(); java.security.PrivateKey pk = keyPair.getPrivate(); // Java API requires a certificate chain X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(), expirationTime); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; String alias = UUID.randomUUID().toString(); keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain); FileOutputStream stream = new FileOutputStream(keyStoreFile); keyStore.store(stream, keyStoreSecret.toCharArray()); PublicKey publicKey = keyPair.getPublic(); JSONObject jsonObject = new JSONObject(); jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily()); jsonObject.put(KEY_ID, alias); jsonObject.put(KEY_USE, Use.SIGNATURE); jsonObject.put(ALGORITHM, signatureAlgorithm.getName()); jsonObject.put(EXPIRATION_TIME, expirationTime); if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus())); jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent())); } else if (publicKey instanceof ECPublicKey) { ECPublicKey ecPublicKey = (ECPublicKey) publicKey; jsonObject.put(CURVE, signatureAlgorithm.getCurve()); jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX())); jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY())); } JSONArray x5c = new JSONArray(); x5c.put(Base64.encodeBase64String(cert.getEncoded())); jsonObject.put(CERTIFICATE_CHAIN, x5c); return jsonObject; }