首页 \ 问答 \ 密码包中哈希函数的哈希值(Hash of hash functions in cryptonite package)

密码包中哈希函数的哈希值(Hash of hash functions in cryptonite package)

我正在尝试使用Crypto.Hash模块 (cryptonite包)并生成“哈希哈希”结果。

问题是模块的散列函数的签名是hashlazy :: HashAlgorithm a => ByteString -> Digest a ,所以在我生成hashlazy (hashlazy x) ,我需要将Digest翻译成ByteString。

虽然提供了digestFromByteString函数,但是没有这样的函数用于反向(可能对所有Digests都没有意义?)。

所以我找到的唯一方法是这样做:

-- produce a hexadecimal string representation of the digest
myHash :: ByteString -> String
myHash b = show (hashlazy bs :: Digest SHA256)

-- convert a hexadecimal string into a ByteString
fromHexString :: String -> ByteString
fromHexString = undefined 

然后我现在可以做hashhash x = myHash $ fromHexString $ myHash x ...

但这看起来非常麻烦。

我的问题:我是否正确使用了库函数? 我错过了某处的转换功能吗? 或者我应该采取不同的做法?

===编辑1 ===

我想保持我的问题简单并避免其他我认为不重要的细节,但我确实需要将哈希结果转换回ByteString,因为我需要在再次散列之前操作它。 例如,

-- myByteString is a constant
-- firstByteString is original input
finalResult = hash $ append myByteString (hash firstByteString)

===编辑2 ===

我接受了本的答案,并从中学习,但为了将来参考,将Crypto.Hash的Digest a转换为ByteString一种方法是通过内存包的 Data.ByteArray模块和pack函数

module Main where

import Data.ByteString
import Data.ByteString as BS (pack)
import Data.ByteArray (ByteArrayAccess)
import qualified Data.ByteArray as BA (unpack)
import Crypto.Hash (Digest, hash)
import Crypto.Hash.Algorithms (SHA256(..))

somehash = hash ("foo" :: ByteString) :: Digest SHA256

toByteString :: ByteArrayAccess a => a -> ByteString
toByteString = BS.pack . BA.unpack

somebytestring = toByteString somehash

I am trying to use the Crypto.Hash module (cryptonite package) and produce "hash of hash" results.

The issue is that the signature of the module's hash function is hashlazy :: HashAlgorithm a => ByteString -> Digest a, so before I can produce a hashlazy (hashlazy x), I'll need to translate a Digest into a ByteString.

Although there is a digestFromByteString function provided, there is no such function for the reverse (maybe it doesn't make sense for all Digests?).

So the only way I found is to do this :

-- produce a hexadecimal string representation of the digest
myHash :: ByteString -> String
myHash b = show (hashlazy bs :: Digest SHA256)

-- convert a hexadecimal string into a ByteString
fromHexString :: String -> ByteString
fromHexString = undefined 

and then I can now do hashhash x = myHash $ fromHexString $ myHash x...

But that looks very cumbersome.

My question: Am I using the library functions properly? Did I miss a conversion function somewhere? Or should I do things differently?

=== EDIT 1 ===

I wanted to keep my question simple and avoided other details which I thought weren't important, but I do need to convert the hash result back into a ByteString, as I need to do manipulate it before hashing again. Eg,

-- myByteString is a constant
-- firstByteString is original input
finalResult = hash $ append myByteString (hash firstByteString)

=== EDIT 2 ===

I accepted ben's answer, and learned from it, but for future reference, one way to convert Crypto.Hash's Digest a into a ByteString is via the memory package's Data.ByteArray module and the pack function :

module Main where

import Data.ByteString
import Data.ByteString as BS (pack)
import Data.ByteArray (ByteArrayAccess)
import qualified Data.ByteArray as BA (unpack)
import Crypto.Hash (Digest, hash)
import Crypto.Hash.Algorithms (SHA256(..))

somehash = hash ("foo" :: ByteString) :: Digest SHA256

toByteString :: ByteArrayAccess a => a -> ByteString
toByteString = BS.pack . BA.unpack

somebytestring = toByteString somehash

原文:https://stackoverflow.com/questions/39556394
更新时间:2022-02-22 14:02

最满意答案

在按钮上添加一个keylistener(使用KeyBindings会更好)。

为当前面板的索引创建两个int变量(例如x,y)。

在keyPressed(KeyEvent e)方法中,从当前面板中删除该按钮并将其添加到新面板。

注意:如果要使用键移动按钮,则按钮必须具有焦点。

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyFrame extends JFrame {

    private JPanel [][] innerCells;
    private JButton b = new JButton("G");
    private int x=0;
    private int y=0;
    private final int size=10;

    public MyFrame() {
        JFrame fr = new JFrame("Final Exams");
        fr.setSize(800, 600);

        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.setVisible(true);
        fr.setLocationRelativeTo(null);

        JPanel p = new JPanel(new GridLayout(size, size));

        innerCells = new JPanel[size][size];

        for(int i=0;i<size;i++){
            for(int j=0;j<size;j++){
                innerCells[i][j] = new JPanel();
                innerCells[i][j].setBorder(BorderFactory.createLineBorder(Color.orange));
               p.add(innerCells[i][j]);
            }
        }
        innerCells[0][0].add(b);
        fr.add(p);  

        b.addKeyListener(new KListener());
    }

    private class KListener extends KeyAdapter{
        public void keyPressed(KeyEvent e){
            innerCells[x][y].remove(b);
            innerCells[x][y].repaint();
            int keyCode = e.getKeyCode();
            switch( keyCode ) { 
                case KeyEvent.VK_UP:
                    x= x-1;
                        break;

                case KeyEvent.VK_DOWN:
                    x= (x+1)%size;
                        break;

                case KeyEvent.VK_LEFT:
                    y= y-1;
                        break;
                case KeyEvent.VK_RIGHT :
                    y= (y+1)%size; 
                        break;
            }
            if(x<0) x=size-1;
            if(y<0)y=size-1;
            innerCells[x][y].add(b);

            innerCells[x][y].revalidate();
            b.requestFocus();
    }
   ´        }

    public static void main(String[] args){
            MyFrame f = new MyFrame();
    }
}

Guys i manage to solve at last this problem! here is the solution..I have done it with KeyListener but i think as @MadProgrammer says with key bindings its easier!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Askhsh6 {

    int gr, st;
    Dimension dim;

    public Askhsh6() {
        final JFrame fr1 = new JFrame("a Title");
        fr1.setSize(800, 600);
        fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr1.setVisible(true);
        fr1.setResizable(false);

        final JButton b = new JButton("G");
        dim = new Dimension(70, 50);
        b.setSize(dim);
        b.setFocusable(false);
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                b.validate();
                b.repaint();
                boolean pop = b.isFocusOwner();

                pop = b.isFocusOwner();
                System.out.println("" + pop);
            }
        });
        final JPanel[][] p;
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(8, 6));

        p = new JPanel[8][6];

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 6; j++) {
                p[i][j] = new JPanel();
                p[i][j].setLayout(new BorderLayout());

                p[i][j].setBorder(BorderFactory.createLineBorder(Color.orange));
                p1.add(p[i][j]);

            }
        }
        p[0][0].add(b, BorderLayout.CENTER);
        gr = st = 0;

        fr1.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent ke) {
                if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
                    System.out.println("DOWN");
                    if (gr + 1 < 8) {
                        p[gr][st].remove(b);
                        gr = gr + 1;
                        p[gr][st].add(b, BorderLayout.CENTER);

                        fr1.repaint();
                    }
                }
                if (ke.getKeyCode() == KeyEvent.VK_UP) {
                    System.out.println("UP");
                    if (gr - 1 >= 0) {
                        p[gr][st].remove(b);
                        gr = gr - 1;
                        p[gr][st].add(b, BorderLayout.CENTER);

                        fr1.repaint();
                    }
                }
                if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
                    System.out.println("LEFT");
                    if (st - 1 >= 0) {
                        p[gr][st].remove(b);
                        st = st - 1;
                        p[gr][st].add(b, BorderLayout.CENTER);

                        fr1.repaint();
                    }
                }
                if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {
                    System.out.println("RIGHT");
                    if (st + 1 < 6) {
                        p[gr][st].remove(b);
                        st = st + 1;
                        p[gr][st].add(b, BorderLayout.CENTER);

                        fr1.repaint();
                    }
                }
            }
        });
        fr1.add(p1);
        fr1.validate();
    }
}

相关问答

更多
  • 在按钮上添加一个keylistener(使用KeyBindings会更好)。 为当前面板的索引创建两个int变量(例如x,y)。 在keyPressed(KeyEvent e)方法中,从当前面板中删除该按钮并将其添加到新面板。 注意:如果要使用键移动按钮,则按钮必须具有焦点。 import java.awt.Color; import java.awt.GridLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; ...
  • JPanel无法获得KeyListener的工作重点。 首选方法是使用键绑定进行Swing。 即使组件没有焦点,您也可以将Action映射到KeyStroke。 键绑定示例 A JPanel cannot gain focus for KeyListener to work. The preferred approach is to use Key Bindings for Swing. You can map an Action to a KeyStroke even when a component d ...
  • 因此,当用户点击特定键时,它会停止自动点击器 是的,您可以将键绑定添加到面板。 更好的方法是为应用程序的各种Actions支持创建一个菜单栏。 然后,您可以使用菜单项来启动/停止点击器。 创建菜单项时,您可以为菜单项指定加速器,菜单项将自动为您创建键绑定。 这是一个更好的解决方案,因为“键绑定”是自我记录,因为它是菜单项的一部分。 阅读Swing教程中有关如何使用菜单的部分, 以获取更多信息和工作示例以帮助您入门。 正如我所说,我想在这里学习。 保留所有Swing基础知识的教程链接。 还有关于“键绑定”和“ ...
  • 而不是addKeyListener(this) write frame.addKeyListener(this) 编辑:欲了解更多信息在这里阅读。 顺便说一下,我不认为在Panel中创建JFrame是一个很好的设计,但这取决于你的设计。 Instead of addKeyListener(this) write frame.addKeyListener(this) Edit: For more information read here. And by the way, I don't think that ...
  • 这是因为你打电话给System.out.println(""); 是错误的:它应该在while循环的结尾(但在其内部 )。 当代码正确缩进时,这很容易看到,如下所示: public static void printCommonLogTable() { double x = 0.0; while (x <= 10.0) { System.out.print(x + " " + Math.log(x) + " "); x = x + 0.5; ...
  • 试试这个公式: =INDEX(A3:A12,MATCH(M2,INDEX(B3:I12,0,MATCH(L2,B2:I2,0)),0)) Try this formula: =INDEX(A3:A12,MATCH(M2,INDEX(B3:I12,0,MATCH(L2,B2:I2,0)),0))
  • 如果你已经完成了任何搜索,你会发现KeyListeners只能在一个组件上工作,如果它具有焦点,对于JPanel意味着使其可聚焦, someJPanel.setFocusable(true)然后将焦点分配给它someJPanel.requestFocusInWindow() 。 您还会看到,如果可能的话,通常要避免使用KeyListeners来支持Key Bindings 。 作为旁注,这让我担心: while(flag){ c.repaint(); } 一段时间真正的循环在Swing GUI中是 ...
  • 如何使用键盘事件像2人游戏一样? 仅为按下的最后一个键生成一个事件,因此基本上您需要跟踪所有按下的键(以及它们被释放时)。 我过去使用带有Swing Timer Key Bindings完成了这个。 查看Motion中使用 KeyboardAnimation找到的KeyboardAnimation示例,以获取此方法的工作示例。 该链接还将解释Key Bindings是什么以及为什么它们应该优先于KeyListener。 How can I do this using keyboard events Like ...
  • 您可以在KeyListener使用Timer ,或者只是跟踪上次按下某个键的时间并将其与当前时间进行比较。 这允许您在到达任何逻辑之前从KeyListener提前退出。 但是,您可以不停止触发KeyListener ,除非您不断删除它并在250 ms后再次添加它。 另请注意,在Swing中,您通常会使用键绑定而不是KeyListener ,尽管它们会有完全相同的问题。 You could use a Timer in the KeyListener, or simply keep track of the ...
  • 您可以注册整个框架的Escape键的侦听器。 Action action = ...; String name = "Escape"; // I think the exact name doesn't matter JComponent pnl = frame.getRootPane(); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); pnl.getActionMap().put(name, action); pn ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)